Skip to content

How to define rules?

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

Bali believes that defining rules should be easy. Full stop.

All rules, by Bali's convention, should be within a single and only single file.

Rules are segmented down in the following way:

  1. The target, or any ruby class.
  2. The subtarget, or the user class.

Define the targets

Assume that you have a class so-called My::Transaction. To define rules for that class, you create a file, for example named as rules.rb and make sure that it is loaded. In those file, the codes will be like this at the beginning:

  Bali.map_rules do
    rules_for My::Transaction do
    end
  end

You can add more classes though:

  Bali.map_rules do
    rules_for My::Transaction do
    end
    rules_for My::User do
    end
    rules_for My::OtherClass do
    end
  end

In each class that you define rules_for, you need to include Bali::Objector so that the class, and its instances, can respond to can?, can!, cannot? and cannot!.

class My::Transaction do
  include Bali::Objector

  # other codes of this class may follow
  # ...
end

Define the subtargets

In Bali, subtarget is a basically the user against which you would like to test whether he/she is authorised or not to do something, on your target.

  Bali.map_rules do
    rules_for My::Transaction do
       describe :finance do
       end
    end
  end

In the above example, My::Transaction is a target, and finance is the subtarget. User that has role/roles of finance, will subject to that code.

There are two types of subtargets, that you should read:

  1. Defining rules for definite subtarget
  2. Defining rules for wildcard/any subtarget

For further read:

  1. User with multiple roles

Define the rules

There are four distinct types of rule:

  1. can indicate a subtarget is authorised to do something
  2. cannot indicate a subtarget is not authorised to do something, if rule is not defined, then user is not authorised by default.
  3. can_all indicates a subtarget is authorised to do everything, unless a cannot code specifically prohibits.
  4. cannot_all indicates a subtarget is not authorised to everything, unless a can code specifically allows.
  Bali.map_rules do
    rules_for My::Transaction do
       describe :finance do
         can :print
       end
    end
  end