Running with Ruby

Tag: Ruby 1.9.2 (page 2 of 15)

Paperclip, Bootstrap and SimpleForm working together on Rails

Few days ago, I’ve decided to get back to the “original” Paperclip. Until now, in one of my projects I’ve been using forked version with additional tweaks. However, supporting it for 3 years was enough. Getting back on track was fairly simple. It took me 1 day to fix the file structure, next day to rewrite validators and that would be all except one thing. Paperclip attaches error to 3 fields (example for thumb file):

  • thumb_file_name
  • thumb_file_size
  • thumb_content_type

I don’t like this idea, since those are basically the internals of Paperclip implementation and in my opinion, all the errors should be attached to the “base” attribute (which in this case is called thumb). Furthermore this is not only the architectural problem but it also affect my views. I use Bootstrap with a SimpleForm attached to it and adding Paperclip to it seams fairly simply:

= simple_form_for @user, :html => { :class => 'form-horizontal' } do |f|
  = f.input :avatar

And… this should be it. However, as I mentioned above, Paperclip attaches errors to fields different than “thumb” (not all of them but it doesn’t matter), so they aren’t displayed on the interface. I could use something like that:

= f.errors :thumb_content_type

and well, this indeed works, unfortunately without any Bootstrap stylings. Also it requires extra line for each attachment that I use. So it sucks! That’s why I’ve decided to do a little hack on it: let’s just copy all the error messages into original “base” attachment name. This should solve our problem (and it did):

# lib/paperclip_extensions.rb
module PaperclipExtensions

  extend ActiveSupport::Concern

  module ClassMethods
    # Changes the default Paperclip behaviour so all the errors from attachments
    # are assigned to an attachment name field instead of 4 different once
    # This allows us to use Bootstrap and SimpleForm without any other extra
    # code
    def has_attached_file(name, options = {})
      # Initialize Paperclip stuff
      super
      # Then create a hookup to rewrite all the errors after validation
      after_validation do
        self.errors[name] ||= []
        %w{file_name file_size content_type updated_at}.each do |field|
          field_errors = self.errors["#{name}_#{field}"]
          next if field_errors.blank?

          self.errors[name] += field_errors
          field_errors.clear
        end
        self.errors[name].flatten!
      end
    end
  end

end

ActiveRecord::Base.send(:include, PaperclipExtensions)

Just put this code into a file in lib/ and create an initializer where you will require it:

# config/initializers/paperclip_extensions.rb
require 'paperclip_extensions'

After that, you are ready to go :) Enjoy using Paperclip with Bootstrap and SimpleForm without any problems!

Ruby Tempfile extension without random postfix

Recently I fell into the “RFM” trap (read fu**ing manual). I had some Ajax files uploaded to my controller and to make it easier, I’ve been processing them using Tempfile class. This was not a problem (I’ve been processing their content) until I’ve decided to do an Ajax file upload which was connected to paperclip. Paperclip saves the file name with extension so when using with Tempfile instance, you might get the invalid file extension.

temp = Tempfile.new(params[:file_name])
temp.binmode
temp.write(Base64.decode64(file[:file_value]))
temp.rewind
temp

The file name is obtained with method path:

temp = Tempfile.new('demo.jpg')
temp.path #=> #<Tempfile:/tmp/demo.jpg20130403-3747-13d19dx>
user.avatar = temp
user.save!

# Paperclip object instance
user.avatar(:big) #=> '/images/users/user_avatar.jpg20130403-3747-13d19dx'

This might be a problem, because some browser won’t render image with invalid extension. However fixing this issue is really easy. It all comes down to reading the manual.

You can provide an Array instance with two elements as a first parameter. The temporary file base name will begin with the array’s first element, and end with the second element:

temp = Tempfile.new(['demo', '.jpg'])
temp.path #=> #<Tempfile:/tmp/demo20130403-3747-13d19dx.jpg>
user.avatar = temp
user.save!

Conclusion

Since this was mentioned in documentation I’ve got a lesson to always read it :)

Olderposts Newerposts

Copyright © 2017 Running with Ruby

Theme by Anders NorenUp ↑