lib/consul/power.rb in consul-0.3.0 vs lib/consul/power.rb in consul-0.4.0

- old
+ new

@@ -1,22 +1,28 @@ module Consul module Power def self.included(base) - base.extend ActiveSupport::Memoizable base.extend ClassMethods + base.send :include, Memoizer end def include?(name, *args) args = args.dup record = args.shift power_value = send(name) - if record.nil? || boolean_or_nil?(power_value) + if record.nil? !!power_value else - power_ids_name = self.class.power_ids_name(name) - send(power_ids_name, *args).include?(record.id) + if scope?(power_value) + power_ids_name = self.class.power_ids_name(name) + send(power_ids_name, *args).include?(record.id) + elsif collection?(power_value) + power_value.include?(record) + else + raise Consul::NoCollection, "can only call #include? on a collection, but power was of type #{power_value.class.name}" + end end end def include!(*args) include?(*args) or raise Consul::Powerless.new("No power to #{args.inspect}") @@ -26,10 +32,18 @@ def boolean_or_nil?(value) [TrueClass, FalseClass, NilClass].include?(value.class) end + def scope?(value) + value.respond_to?(:scoped) + end + + def collection?(value) + value.is_a?(Array) || value.is_a?(Set) + end + module ClassMethods def power(name, &block) define_method(name, &block) define_method("#{name.to_s}?") { |*args| include?(name, *args) } @@ -54,9 +68,20 @@ def power_ids_name(name) "#{name.to_s.singularize}_ids" end attr_accessor :current + + def with_power(inner_power, &block) + unless inner_power.is_a?(self) + inner_power = new(inner_power) + end + old_power = current + self.current = inner_power + block.call + ensure + self.current = old_power + end end end end