Module: Spleen

Defined in:
lib/spleen.rb,
lib/generators/spleen/install_generator.rb

Defined Under Namespace

Modules: Base, Generators

Constant Summary collapse

VERSION =
'0.0.2'

Class Method Summary collapse

Class Method Details

.extended(model_class) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/spleen.rb', line 6

def self.extended(model_class)
  model_class.instance_eval do
    extend Base
  end

  model_class.class_eval do
    ##
    # @param [Float] value
    # @param [ActiveRecord::Base] ratetor
    # @return [Boolean] TrueClass is rate saved else FalseClass
    #
    def rate(value, ratetor)
      r = Rating.new(
        :ratetor => ratetor,
        :rateable_type => ratetor.class.to_s,
        :rate => value,
        :rateable => self,
        :rateable_type => self.class.to_s,
        :rateable_id => self.id
      )
      if r.valid?
        r.save
      else
        r.errors.full_messages.each do |e|
          self.errors.add(:base, e)
        end
        false
      end
    end

    ##
    # Helper method that returns the average rating
    #
    def average_rate
      Rating.calculate(:average, :rate,
                       :conditions => {
        :rateable_type => self.class.to_s,
        :rateable_id => self.id
      }).to_f
    end
    ##
    # Helper method that returns the sum rate
    #
    def sum_rate
      Rating.calculate(:sum, :rate,
                       :conditions => {
        :rateable_type => self.class.to_s,
        :rateable_id => self.id
      }).to_i
    end
    ##
    # Helper method that returns the count rate
    #
    def count_rate
      Rating.calculate(:count, :rate,
                       :conditions => {
        :rateable_type => self.class.to_s,
        :rateable_id => self.id
      }).to_i
    end
  end
end