我需要在关注点内的实例方法中访问类方法(在ClassMethods中定义)。
我的大脑融化了,我确信这是一件很简单的事情,我做错了。
我需要访问comparable_opts
内的comparison
。我该怎么办?
按照以下网址摘要:
关注
# app/models/concerns/compare.rb
module Compare
extend ActiveSupport::Concern
attr_accessor :comparable_opts
module ClassMethods
attr_reader :arguable_opts
def comparable_opts
@@comparable_opts
end
private
def default_opts
@default_opts ||= {fields: [:answers_count,
:answers_correct_count,
:answers_correct_rate,
:users_count]}
end
def compare(opts={})
@comparable_opts = default_opts.merge(opts)
end
end
def comparison
end
end
模型
# app/models/mock_alternative.rb
class MockAlternative < ActiveRecord::Base
include Compare
belongs_to :mock, primary_key: :mock_id, foreign_key: :mock_id
compare fields: [:answers_count, :question_answers_count, :question_answers_rate],
with: :mock_aternative_school
def question_answers_rate
self[:answers_count].to_f/self[:question_answers_count].to_f
end
end
答案 0 :(得分:2)
<强>解决方案:强>
我在我的方法cattr_accessor
中使用了compare
。谢谢大家。
module Compare
extend ActiveSupport::Concern
module ClassMethods
attr_reader :arguable_opts
def comparison_klass
"ActiveRecord::#{comparable_opts[:with].to_s.classify}".constantize
end
private
def default_opts
@default_opts ||= {fields: [:answers_count,
:answers_correct_count,
:answers_correct_rate,
:users_count]}
end
def compare(opts={})
cattr_accessor :comparable_opts
self.comparable_opts = default_opts.merge(opts)
end
end
def comparison
comparable_opts
end
end