class Dry::Ability::RulesBuilder

Creates a container with ability rules and provides DSL to define them.

Public Instance Methods

can(actions, subjects, filter: nil, scope: nil, inverse: false, explicit_scope: true, **constraints, &block) click to toggle source

Registers rule in the calculated key

@example

can :read, :public
# File lib/dry/ability/rules_builder.rb, line 61
def can(actions, subjects, filter: nil, scope: nil, inverse: false, explicit_scope: true, **constraints, &block)
  @_container.namespace(:rules) do |_rules|
    Rule.new(actions, subjects,
      constraints: constraints,
      filter:      (filter || block&.to_proc),
      scope:       scope,
      inverse:     inverse,
      explicit_scope: explicit_scope
    ).register_to(_rules)
  end
end
cannot(*args, **options, &block) click to toggle source

@see can(*args, **options, &block)

# File lib/dry/ability/rules_builder.rb, line 74
def cannot(*args, **options, &block)
  can(*args, **options, inverse: true, &block)
end
map(kind, dict) click to toggle source

Registers mappings

@example

map :action,  :read   => %i(index show)
map :subject, :public => %w(Post Like Comment)
# File lib/dry/ability/rules_builder.rb, line 24
def map(kind, dict)
  kind = T::ActionOrSubject[kind]
  dict = T::RulesMapping[dict]

  @_container.namespace(:mappings) do |_mappings|
    _mappings.namespace(kind) do |_action_or_subject|
      dict.each do |mapped, list|
        list.sort.each do |original|
          key = _action_or_subject.send(:namespaced, original)
          pred = Array.wrap(@_container._container.delete(key)&.call)
          pred << mapped unless pred.include?(mapped)
          _action_or_subject.register(original, pred)
        end
      end
    end
  end
end
map_action(dict) click to toggle source

Shorthand of map :action, dict

# File lib/dry/ability/rules_builder.rb, line 43
def map_action(dict)
  map :action, dict
end
map_subject(dict) click to toggle source

Shorthand of map :subject, dict

@exmaple

map_subject :public => %w(Post Like Comment)
# File lib/dry/ability/rules_builder.rb, line 52
def map_subject(dict)
  map :subject, dict
end
mixin() click to toggle source

Generates module, which, after being included into a class, registers singleton instance variable @_container as reference to the composed container of rules.

Calls superclass method
# File lib/dry/ability/rules_builder.rb, line 80
def mixin
  @mixin ||= Module.new.tap do |mod|
    container = @_container.freeze
    mod.define_singleton_method :included do |base|
      base.instance_variable_set(:@_container, container)
      super(base)
    end
    mod
  end
end