added :if and :unless conditionals to impressionist

This commit is contained in:
Bashir Eghbali 2014-02-21 13:13:33 -08:00
parent 1c3ac147aa
commit 2e5dabe9b3
1 changed files with 14 additions and 5 deletions

View File

@ -3,7 +3,7 @@ require 'digest/sha2'
module ImpressionistController module ImpressionistController
module ClassMethods module ClassMethods
def impressionist(opts={}) def impressionist(opts={})
before_filter { |c| c.impressionist_subapp_filter(opts[:actions], opts[:unique])} before_filter { |c| c.impressionist_subapp_filter(opts)}
end end
end end
@ -13,7 +13,7 @@ module ImpressionistController
end end
def impressionist(obj,message=nil,opts={}) def impressionist(obj,message=nil,opts={})
unless bypass unless bypass || !should_count_impression?(opts[:if]) || should_count_impression?(opts[:unless])
if obj.respond_to?("impressionable?") if obj.respond_to?("impressionable?")
if unique_instance?(obj, opts[:unique]) if unique_instance?(obj, opts[:unique])
obj.impressions.create(associative_create_statement({:message => message})) obj.impressions.create(associative_create_statement({:message => message}))
@ -29,10 +29,11 @@ module ImpressionistController
@impressionist_hash = Digest::SHA2.hexdigest(Time.now.to_f.to_s+rand(10000).to_s) @impressionist_hash = Digest::SHA2.hexdigest(Time.now.to_f.to_s+rand(10000).to_s)
end end
def impressionist_subapp_filter(actions=nil,unique_opts=nil) def impressionist_subapp_filter(opts = {})
unless bypass unless bypass || !should_count_impression?(opts[:if]) || should_count_impression?(opts[:unless])
actions = opts[:actions]
actions.collect!{|a|a.to_s} unless actions.blank? actions.collect!{|a|a.to_s} unless actions.blank?
if (actions.blank? || actions.include?(action_name)) && unique?(unique_opts) if (actions.blank? || actions.include?(action_name)) && unique?(opts[:unique])
Impression.create(direct_create_statement) Impression.create(direct_create_statement)
end end
end end
@ -59,6 +60,14 @@ module ImpressionistController
Impressionist::Bots.bot?(request.user_agent) Impressionist::Bots.bot?(request.user_agent)
end end
def should_count_impression?(condition)
if condition.present?
condition.is_a?(Symbol) ? self.send(condition) : condition.call
else
true
end
end
def unique_instance?(impressionable, unique_opts) def unique_instance?(impressionable, unique_opts)
return unique_opts.blank? || !impressionable.impressions.where(unique_query(unique_opts)).exists? return unique_opts.blank? || !impressionable.impressions.where(unique_query(unique_opts)).exists?
end end