Module: Rating::Extension::ClassMethods

Defined in:
lib/rating/models/rating/extension.rb

Instance Method Summary collapse

Instance Method Details

#rating(options = {}) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/rating/models/rating/extension.rb', line 67

def rating(options = {})
  after_create -> { rating_warm_up scoping: options[:scoping] }, unless: -> { options[:as] == :author }

  has_many :rating_records,
    as:         :resource,
    class_name: '::Rating::Rating',
    dependent:  :destroy

  has_many :rates_records,
    as:         :resource,
    class_name: '::Rating::Rate',
    dependent:  :destroy

  has_many :rated_records,
    as:         :author,
    class_name: '::Rating::Rate',
    dependent:  :destroy

  scope :order_by_rating, lambda { |opts = {}|
    column = opts.fetch(:column, :estimate)
    direction = opts.fetch(:direction, :desc)
    scope = opts[:scope]
    base_class = scope&.class&.base_class

    includes(:rating_records)
      .where(Rating.table_name => { scopeable_id: scope&.id, scopeable_type: base_class&.name })
      .order("#{Rating.table_name}.#{column} #{direction}")
  }

  define_method :rating_options do
    options
  end
end