Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a class method (or variable) in an instance method using concern?

I need to access a class method (defined in ClassMethods) in an instance method inside a concern.

My brain is melted and I'm sure that is a simple thing that I'm doing wrong.

I need to access comparable_opts inside comparison. How can I do it?

Follow snippets below:

Concern

# 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

Model

# 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
like image 318
joaofraga Avatar asked May 23 '26 06:05

joaofraga


1 Answers

Solution: I've just used cattr_accessor in my method compare. Thank everyone.

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
like image 90
joaofraga Avatar answered May 26 '26 03:05

joaofraga