- Userモデル
- job_id: references
- Jobモデル
- klass: string
を考える
class User < ApplicationRecord
belongs_to :job
end
class Job < ApplicationRecord
has_many :users
def method_missing(name, *args)
fail if klass.blank? || self.class.included_modules.include?("Modules::#{self.klass.camelize}".constantize)
extend("Modules::#{self.klass.camelize}".constantize)
send(name, *args) and return if respond_to?(name)
fail
end
end
module Modules
module Engineer
def bark
p 'hoge'
end
end
end
engineer = Job.create(klass: 'engineer')
user = User.create(job: engineer)
user.job.bark # => hoge
やや冗長だけどやや安全版↓
(decoratorパターンになってしまった)
class User < ApplicationRecord
belongs_to :job
end
class Job < ApplicationRecord
has_many :users
def bark
fail
end
def mixined
klass.present? ? extend("Modules::#{self.klass.camelize}".constantize) : self
end
end
module Modules
module Engineer
def bark
p 'hoge'
end
end
end
engineer = Job.create(klass: 'engineer')
user = User.create(job: engineer)
user.job.mixined.bark # => hoge
完
というのは嘘で素直にSTIしたほうが良いのではないでしょうか。