Skip to content

Defining rules for definite subtarget

Adam Pahlevi Baihaqi edited this page Sep 24, 2015 · 4 revisions

As we learned from the ways rules are defined, rules can be defined within definite subtarget, or wildcard subtarget.

We will look at more detail on how to define rules for definite subtarget. But first, what is definite subtarget?

A definite subtarget is simply code of blocks where you can define rules, specifically for the subtarget in question.

Defining using arrays

For simple rule, or one-liner, rules can be defined using array:

Bali.map_rules do
  rules_for My::Transaction do
    describe "general user", can: [:update, :edit], cant: [:delete]
  end
end

When defining the subtarget, "general user" and :general_user is the same thing, so either one can be used although it may be a better idea to use a symbol instead.

By default, if rule is undefined, it will be cant so the above code is redundant. It can be written just fine as:

    describe "general user", can: [:update, :edit]

Defining using blocks

Rules can also be defined using blocks, and probably, this is the most common ways which one would employ to define rules:

Bali.map_rules do
  rules_for My::Transaction, as: :transaction do
    describe(:supreme_user) { can_all }
    describe :admin_user do
      can_all
      cannot :delete
    end
end

There are four access verbs you can use to define a rule:

  1. cant_all
  2. can_all
  3. can
  4. cannot

Read more about them here.

can and cannot can take array, for example:

    describe "finance user" do
      can :update, :delete, :edit
    end

Defining for multiple subtargets

It is possible for a rule to be defined for multiple subtargets at once:

  Bali.map_rules do
    rules_for My::Transaction do
      # rules described bellow will affect both :general_user and :finance_user
      describe :general_user, :finance_user do
        can :update, :edit
      end
    end
  end