Sha256: 5e524782fff0367f832003949e807957c7bd6ca8478f7e452ca84ff7b0320d00

Contents?: true

Size: 1.74 KB

Versions: 1

Compression:

Stored size: 1.74 KB

Contents

# encoding: UTF-8
require 'rails'

module Spleen
  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

  module Base
    def spleen(opts={})
      options = {:as => :rateable}
      options.merge!(opts)
      has_many :ratings, options
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
spleen-0.0.1 lib/spleen.rb