Class: Organizations::Roles::RoleBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/organizations/roles.rb

Overview

DSL builder for custom role definitions

Instance Method Summary collapse

Constructor Details

#initializeRoleBuilder

Returns a new instance of RoleBuilder.



204
205
206
207
# File 'lib/organizations/roles.rb', line 204

def initialize
  @roles = {}
  @current_role = nil
end

Instance Method Details

#can(permission) ⇒ Object

Add a permission to the current role

Parameters:

  • permission (Symbol)

    Permission to add



225
226
227
228
229
# File 'lib/organizations/roles.rb', line 225

def can(permission)
  raise "can must be called within a role block" unless @current_role

  @roles[@current_role][:permissions] << permission.to_sym
end

#role(name, inherits: nil) { ... } ⇒ Object

Define a role with optional inheritance

Parameters:

  • name (Symbol)

    Role name

  • inherits (Symbol, nil) (defaults to: nil)

    Role to inherit from

Yields:

  • Block to define permissions



213
214
215
216
217
218
219
220
221
# File 'lib/organizations/roles.rb', line 213

def role(name, inherits: nil, &block)
  @roles[name] = {
    inherits: inherits,
    permissions: []
  }
  @current_role = name
  instance_eval(&block) if block_given?
  @current_role = nil
end

#to_permissionsHash<Symbol, Array<Symbol>>

Build final permissions hash with inheritance resolved

Returns:

  • (Hash<Symbol, Array<Symbol>>)


233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/organizations/roles.rb', line 233

def to_permissions
  result = {}

  # Process roles in reverse hierarchy order (lowest first)
  # so inheritance works correctly
  Roles::HIERARCHY.reverse_each do |role_name|
    next unless @roles.key?(role_name)

    role_def = @roles[role_name]
    perms = role_def[:permissions].dup

    # Add inherited permissions
    if role_def[:inherits] && result.key?(role_def[:inherits])
      perms = (result[role_def[:inherits]] + perms).uniq
    end

    result[role_name] = perms.freeze
  end

  result.freeze
end