Class: Popstar::RuleGroup

Inherits:
Object
  • Object
show all
Defined in:
lib/popstar/rule_group.rb

Instance Method Summary collapse

Constructor Details

#initialize(target, &block) ⇒ RuleGroup

Returns a new instance of RuleGroup.



3
4
5
6
# File 'lib/popstar/rule_group.rb', line 3

def initialize(target, &block)
  @target = target
  instance_eval(&block) if block_given?
end

Instance Method Details

#on(action, model, *args) ⇒ Object



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
# File 'lib/popstar/rule_group.rb', line 8

def on(action, model, *args)
  options = args.extract_options!
  options.reverse_merge!(
    :rate => 1
  )

  rate = begin
    if options[:rate].respond_to?(:call)
      options[:rate]
    else
      proc { options[:rate] }
    end
  end

  target = @target

  if Popstar::Migration.rules[target].present?
    Popstar::Migration.rules[target] << { :action => action, :model => model, :rate => rate }
  else
    Popstar::Migration.rules[target] = [{ :action => action, :model => model, :rate => rate }]
  end

  increase_popularity = proc do |model|
    model.send(target).inc(:popularity, rate.call(model))
  end

  decrease_popularity = proc do |model|
    model.try(:send, target).try(:inc, :popularity, -rate.call(model))
  end

  model.send("after_#{action}", increase_popularity)
  model.send("after_destroy", decrease_popularity) if action == :create
end