Skip to content

Commit

Permalink
Allow using callable objects as scopes #261
Browse files Browse the repository at this point in the history
  • Loading branch information
killondark committed May 7, 2024
1 parent ce22e5a commit 670f557
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/action_policy/policy/scoping.rb
Expand Up @@ -90,6 +90,8 @@ def included(base)
# If `type` is not specified then we try to infer the type from the
# target class.
def apply_scope(target, type:, name: :default, scope_options: nil)
# binding.pry

raise ActionPolicy::UnknownScopeType.new(self.class, type) unless
self.class.scoping_handlers.key?(type)

Expand All @@ -113,8 +115,11 @@ def lookup_type_from_target(target)

module ClassMethods # :nodoc:
# Register a new scoping method for the `type`
def scope_for(type, name = :default, &block)
def scope_for(type, name = :default, callable = nil, &block)
name, callable = prepare_args(name, callable)

mid = :"__scoping__#{type}__#{name}"
block = ->(target) { callable.call(target) } if callable

define_method(mid, &block)

Expand Down Expand Up @@ -154,6 +159,14 @@ def scope_matchers
[]
end
end

private

def prepare_args(name, callable)
return [name, callable] if name && callable
return [name, nil] if name.is_a?(Symbol) || name.is_a?(String)
[:default, name]
end
end
end
end
Expand Down

0 comments on commit 670f557

Please sign in to comment.