user4687077 user4687077 - 10 days ago 5
Ruby Question

How to DRY has_attached_file that I write in 5 models

This is my code that I write in 5 different models (same code).

has_attached_file :image,
s3_region: 'ap-northeast-1',
storage: :s3,
s3_protocol: :https,
s3_credentials: "#{Rails.root}/config/amazon_s3.yml",
url: ':s3_domain_url',
path: '/images/:id/:filename',
s3_host_alias: 'https://s3-ap-northeast-1.amazonaws.com/'


Is there any way to DRY it out so that I have it only in one place and use it in different models?

Answer

Sure, you can use concenrs.

# models/concenrs/attachable.rb
module Attachable
  extend ActiveSupport::Concern

  included do
    has_attached_file :image,
      s3_region: 'ap-northeast-1',
      storage: :s3,
      s3_protocol: :https,
      s3_credentials:  "#{Rails.root}/config/amazon_s3.yml",
      url: ':s3_domain_url',
      path:  '/images/:id/:filename',
      s3_host_alias: 'https://s3-ap-northeast-1.amazonaws.com/'
  end
end

In model:

class User < ApplicationRecord
  include Attachable
end
Comments