<img src=“https://codeclimate.com/github/mattways/attachs.png” /> <img src=“https://travis-ci.org/mattways/attachs.png?branch=master” alt=“Build Status” /> <img src=“https://gemnasium.com/mattways/attachs.png” alt=“Dependency Status” />
Attachs
Minimalistic toolkit to attach file and images to records.
Install
Put this line in your Gemfile:
gem 'attachs'
Then bundle:
$ bundle
ImageMagick must be install, you can install it with homebrew:
brew install imagemagick
Usage
Mount the engine at the end of you routes.rb (only if you are using local storage):
mount Attachs:Engine: '/' # Will be use to generate on the fly missing image presets
Add the column to your table (just a string):
create_table :models do |t|
t.string :attr
end
If you need a file:
class Model < ActiveRecord::Base
has_attached_file :attr, default: 'file.txt'
end
If you need a image:
class Model < ActiveRecord::Base
has_attached_image :attr, presets: [:small, :big], default: 'assets/image.jpg'
end
Define presets in your application.rb
config.attachs.presets = {
big: { method: :fit, width: 1024, height: 768 }, # Fit will scale the image until it fit in the space without cropping
small: { method: :fill, width: 120, height: :120 }, # Fill will scale the image to fill all the space and then crop
custom: proc { |image| image.convert resize: '100x100' } # ImageMagick wrapper to do whatever you want
}
config.attachs.default_presets = [:small] # Define the default presets for all models with attached images
config.attachs.storage = :local # The default it's local, you can use :s3 as well
If you want to use S3 create a s3.yml config file with this generator and complete it:
rails g attachs:s3:config
The validation works very similar to paperclip:
class Model < ActiveRecord::Base
has_attached_file :attr
validates :attr, attachment_presence: true, attachment_size: { in: 0..4.megabytes }, attachment_content_type: { in: ['txt'] }
end
If you want to translate the errores the keys are:
errors..
errors.. # :max and :min
errors.. # :count
errors.. # :count
errors.. # :types
In your views:
a{ href: record.file.url } # To get the file url
a{ href: record.image.url } # To get the original image
a{ href: record.image.url(:big) } # To get the a thumb
In your forms:
= f.file_field :attr
If your file it’s optional:
= f.check_box :delete_attr
FAQ
How can I use a cdn with this plugin?
Define a base url in your application.rb:
config.attachs.base_url = 'http://cdn.example.com'
How can I automatically create buckets?
Use this rake task after create the s3.yml file:
rake attachs:s3:buckets:create
How can I clean a preset?
Use this rake task:
rake attachs:presets:clean MODEL=models PRESETS=first_preset,second_preset
How can I refresh a preset?
Use this rake task:
rake attachs:presets:refresh MODEL=models PRESETS=first_preset,second_preset
How can I migrate from versions before 0.3.0
All will work the same except from the name of the config parameter, replace uploads with attachs.