Attachs
Json based attachments for records in rails.
Why
I did this gem to:
- Save attachments into one json column.
- Handle multiple attachments without the need of a separate model.
- Have a way to delete orphan files.
- Use graphicsmagick out of the box.
- Delete and rename attachments asynchronous.
- Keep renamed files to improve seo.
Install
Put this line in your Gemfile:
gem 'attachs'
Then bundle:
$ bundle
To install GraphicsMagick you can use homebrew:
$ brew install graphicsmagick
Configuration
Generate the configuration file:
$ bundle exec rails g attachs:install
Set the global settings:
Attachs.configure do |config|
config. = '-strip -quality 82'
config.region = 'us-east-1'
config.bucket = 'some-bucket'
config.base_url = 'https://cdn.mydomain.com'
config.interpolation :name do |record|
record.name
end
end
Usage
Definitions
Add the columns to your tables:
class AddAttachments < ActiveRecord::Migration
def change
add_column :shops, :logo, :jsonb, default: {}
add_column :products, :pictures, :jsonb, default: []
end
end
Define the attachments in your models:
class Shop < ActiveRecord::Base
(
:logo,
path: ':id/:name.png',
default_path: 'missing.png'
)
end
class Product < ActiveRecord::Base
(
:pictures,
path: ':id/:style.:extension',
styles: {
tiny: '25x25',
small: '150x150#',
medium: '300x300!',
large: '600x'
}
)
end
NOTE: The out of the box interpolations are: filename, basename, extension, attribute, content_type, size.
Validations
To validate the presence of the attachment:
class User < ActiveRecord::Base
:pictures
:pictures
end
To validate the size of the attachment:
class User < ActiveRecord::Base
:pictures
:pictures, in: 1..5.megabytes
end
To validate the content type of the attachment:
class User < ActiveRecord::Base
:pictures
:pictures, with: /\Aimage/
end
NOTE: Look into lib/attachs/locales yamls to known the keys.
Forms
Your forms continue to work the same:
<%= form_for @shop do |f| %>
<%= f.file_field :logo %>
<% end %>
You can manage collections with fields_for:
<%= form_for @product do |f| %>
<%= f.fields_for :pictures do |ff| %>
<%= ff.file_field :value %>
<%= ff.number_field :position %>
<% end %>
<% end %>
Urls
The url method points to the original file:
<%= image_tag shop.logo.url %>
To point to some particular style:
<%= image_tag shop.logo.url(:small) %>
Tasks
To reprocess all styles:
$ bundle exec rake attachs:reprocess
To fix missing styles:
$ bundle exec rake attachs:fix_missings
To remove orphan files:
$ bundle exec rake attachs:clear
Contributing
Any issue, pull request, comment of any kind is more than welcome!
I will mainly ensure compatibility to PostgreSQL, AWS, Redis, Elasticsearch, FreeBSD and Memcached.
Credits
This gem is maintained and funded by mmontossi.
License
It is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.