lib/heimdallr/evaluator.rb in heimdallr-1.0.0.RC2 vs lib/heimdallr/evaluator.rb in heimdallr-1.0.0
- old
+ new
@@ -26,12 +26,13 @@
# @group DSL
# Define a scope. A special +:fetch+ scope is applied to any other scope
# automatically.
#
- # @overload scope(name, block)
- # This form accepts an explicit lambda.
+ # @overload scope(name, block=nil)
+ # This form accepts an explicit lambda. If omitted, a scope will be
+ # defined to include all possible records.
#
# @example
# scope :fetch, -> { where(:protected => false) }
#
# @overload scope(name)
@@ -43,12 +44,16 @@
# scoped
# else
# where(:invisible => false)
# end
# end
- def scope(name, explicit_block, &implicit_block)
- @scopes[name] = explicit_block || implicit_block
+ def scope(name, explicit_block=nil, &implicit_block)
+ unless [:fetch, :delete].include?(name)
+ raise "There is no such scope as #{name}"
+ end
+
+ @scopes[name] = explicit_block || implicit_block || -> { scoped }
end
# Define allowed operations for action(s).
#
# The +fields+ parameter accepts both Arrays and Hashes.
@@ -96,11 +101,11 @@
# @param [Symbol, Array<Symbol>] actions one or more action names
# @param [Array<Symbol>] fields field list
def cannot(actions, fields)
Array(actions).map(&:to_sym).each do |action|
@allowed_fields[action] -= fields.map(&:to_sym)
- @fixtures.delete_at *fields
+ fields.each { |field| @fixtures.delete field }
end
end
# @endgroup
@@ -138,24 +143,24 @@
{
operations: [ :view, :create, :update ].select { |op| can? op }
}
end
- # Compute the restrictions for a given +context+. Invokes a +block+ passed to the
- # +initialize+ once.
+ # Compute the restrictions for a given +context+ and possibly a specific +record+.
+ # Invokes a +block+ passed to the +initialize+ once.
#
# @raise [RuntimeError] if the evaluated block did not define a set of valid restrictions
- def evaluate(context)
- if context != @last_context
+ def evaluate(context, record=nil)
+ if [context, record] != @last_context
@scopes = {}
@allowed_fields = Hash.new { [] }
@validators = Hash.new { [] }
@fixtures = Hash.new { {} }
@allowed_fields[:view] += [ :id ]
- instance_exec context, &@block
+ instance_exec context, record, &@block
unless @scopes[:fetch]
raise RuntimeError, "A :fetch scope must be defined"
end
@@ -164,10 +169,10 @@
end
[@scopes, @allowed_fields, @validators, @fixtures].
map(&:freeze)
- @last_context = context
+ @last_context = [context, record]
end
self
end
\ No newline at end of file