LoginSignup
0
0

More than 3 years have passed since last update.

Railsでカラムの値によって動的にmixinする

Last updated at Posted at 2019-07-14
  • 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したほうが良いのではないでしょうか。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0