Working with Paperclip images before save
I'm saving an image upload using Paperclip in Rails, which is working fine.
has_attached_file :image, :styles =&开发者_如何转开发gt; {
:small => "80x90#"
}
What I would to is then save a copy of the small image as a base64 encoded string in the model, when the model is created.
before_update :encode_image
private
def encode_image
self.base64 = ActiveSupport::Base64.encode64(open(self.image.path(:small)).to_a.join)
end
The code above works a treat on update, if the image has previously been saved. I would to apply this logic to a callback that fires before the model saves, but after the images have been processed.
I had thought that after_post_process
would be my saviour, but the path is not fully formed at the point (missing the id).
What am I missing?
Rich
Workaround
My workaround has been to do the following, but it seems a shame run that encode routine every time you update the model:
after_save :encode_image
private
def encode_image
unless self.image.path(:small).blank?
b64 = ActiveSupport::Base64.encode64(open(self.image.path(:small)).to_a.join)
unless self.base64 == b64
self.update_attribute :base64, b64
end
end
end
My workaround has been to do the following, but it seems a shame run that encode routine every time you update the model:
after_save :encode_image
private
def encode_image
unless self.image.path(:small).blank?
b64 = ActiveSupport::Base64.encode64(open(self.image.path(:small)).to_a.join)
unless self.base64 == b64
self.update_attribute :base64, b64
end
end
end
精彩评论