27. クラスメソッドを提供するmodule が必要
class Photo
include Uploader
mount_uploader :foo
end
module Uploader
def self.included base
p "included by #{base}"
base.extend ClassMethods
end
module ClassMethods
def mount_uploader field
p "setting #{field}"
end
end
end
28. 面倒なので ActiveSupport::Concern 使う
module Uploader
extend ActiveSupport::Concern
included do
class << self
def mount_uploader field
p "setting #{field}"
end
end
end
end
30. def mount_uploader field
set_name = "#{field}=".to_sym
class_eval <<-EOS
def #{field}
end
def #{set_name} file
end
EOS
end
class_eval を使ってオーバーライド
31. 独自Classを雑に用意して carrierwave の代表的なメソッドを作る
class BaseUploader
def initialize model, field
@model = model
@field = field
end
def exists?
end
def read
end
def download local_path
end
def path
end
def url
37. module Uploader
extend ActiveSupport::Concern
included do
class << self
@@uploaders = []
def mount_uploader field
@@uploaders << field
end
end
end
end
class Photo
include Uploader
mount_uploader :foo
mount_uploader :bar
end
40. ActiveSupport の class_attribute を使う
module Uploader
extend ActiveSupport::Concern
included do
class_attribute :uploaders
self.uploaders = []
class << self
def mount_uploader field
uploaders << field
end
end
end
end