Module: SinatraResource::Roles::ClassMethods

Defined in:
lib/roles.rb

Instance Method Summary collapse

Instance Method Details

#role(arg) ⇒ Object

High-level way to define a role. You can also specify what role it builds upon (its parent).

For example:

role :anonymous
role :basic => :anonymous
role :admin => :basic

This means: admin > basic > anonymous

The order of the role statements does not matter. Only the dependencies between a role and its parent are significant.

Roles do not have to be a single linear ordering. You can have any number of roles, connected in a DAG (directed acyclic graph). For example:

role :anonymous
role :basic   => :anonymous
role :editor  => :basic
role :manager => :basic
role :admin   => [:editor, :manager]

# which means:
# * admin > manager > basic > anonymous
# * admin > editor  > basic > anonymous
# * manager and editor cannot be compared

Parameters:

  • arg (Symbol, Hash<Symbol => [Symbol, Array<Symbol>]>)


40
41
42
43
44
45
46
47
48
49
50
# File 'lib/roles.rb', line 40

def role(arg)
  if arg.is_a?(Symbol)
    create_role(arg)
  elsif arg.is_a?(Hash)
    arg.each_pair do |name, parent_name|
      create_role(name, parent_name)
    end
  else
    raise ArgumentError
  end
end

#satisfies?(role, minimum) ⇒ Boolean

Is role at least as privileged as minimum?

Examples:

satisfies?(:anonymous, :basic) # => false
satisfies?(:admin,     :basic) # => true
satisfies?(:basic,     :basic) # => true

Parameters:

  • role (Symbol)

    a role (such as :anonymous, :basic, or :admin)

  • minimum (Symbol)

Returns:

  • (Boolean)


65
66
67
68
69
# File 'lib/roles.rb', line 65

def satisfies?(role, minimum)
  @satisfies_cache[[role, minimum]] ||= (
    role == minimum || ancestors(role).include?(minimum)
  )
end

#setupObject



71
72
73
74
75
# File 'lib/roles.rb', line 71

def setup
  @role_config = {}
  @satisfies_cache = {}
  create_role(:nobody)
end

#validate_role(role) ⇒ Symbol

Return role if it is defined, raise exception otherwise.

Returns:

  • (Symbol)

Raises:



82
83
84
85
86
87
88
# File 'lib/roles.rb', line 82

def validate_role(role)
  if @role_config.include?(role)
    role
  else
    raise UndefinedRole, "#{role.inspect} not defined"
  end
end