lib/consul/power.rb in consul-0.4.2 vs lib/consul/power.rb in consul-0.5.0

- old
+ new

@@ -11,16 +11,21 @@ record = args.shift power_value = send(name) if record.nil? !!power_value else + # record is given if power_value.nil? false - elsif scope?(power_value) - power_ids_name = self.class.power_ids_name(name) - send(power_ids_name, *args).include?(record.id) - elsif collection?(power_value) + elsif Util.scope?(power_value) + if Util.scope_selects_all_records?(power_value) + true + else + power_ids_name = self.class.power_ids_name(name) + send(power_ids_name, *args).include?(record.id) + end + elsif Util.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 @@ -34,39 +39,16 @@ 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) } - define_method("#{name.to_s}!") { |*args| include!(name, *args) } - define_method("#{name.to_s.singularize}?") { |*args| include?(name, *args) } - define_method("#{name.to_s.singularize}!") { |*args| include!(name, *args) } - ids_method = power_ids_name(name) - define_method(ids_method) do |*args| - scope = send(name, *args) - scope = scope.scoped(:select => "`#{scope.table_name}`.`id`") - query = if scope.respond_to?(:to_sql) - scope.to_sql - else - scope.construct_finder_sql({}) - end - ::ActiveRecord::Base.connection.select_values(query).collect(&:to_i) + def power(*names, &block) + names.each do |name| + define_power(name, &block) end - memoize ids_method - name end def power_ids_name(name) "#{name.to_s.singularize}_ids" end @@ -80,9 +62,28 @@ old_power = current self.current = inner_power block.call ensure self.current = old_power + end + + private + + def define_power(name, &block) + define_method(name, &block) + define_method("#{name.to_s}?") { |*args| include?(name, *args) } + define_method("#{name.to_s}!") { |*args| include!(name, *args) } + define_method("#{name.to_s.singularize}?") { |*args| include?(name, *args) } + define_method("#{name.to_s.singularize}!") { |*args| include!(name, *args) } + ids_method = power_ids_name(name) + define_method(ids_method) do |*args| + scope = send(name, *args) + scope = scope.scoped(:select => "`#{scope.table_name}`.`id`") + query = Util.scope_to_sql(scope) + ::ActiveRecord::Base.connection.select_values(query).collect(&:to_i) + end + memoize ids_method + name end end end