Class: YiffSpace::Auth::Permissions

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/yiffspace/auth/permissions.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Extensions::Enumerable::Parallel

#parallel_each, #parallel_map

Constructor Details

#initialize(perms) ⇒ Permissions

Returns a new instance of Permissions.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/yiffspace/auth/permissions.rb', line 12

def initialize(perms)
  @values = perms
  @tree   = {}

  perms.each do |perm|
    current = @tree
    parts   = perm.split(".")

    parts.each do |part|
      current[part] ||= {}
      current       = current[part]
    end

    # mark leaf
    current[:__leaf__] = true
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *_args) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/yiffspace/auth/permissions.rb', line 45

def method_missing(name, *_args)
  str = name.to_s

  if str.end_with?("?")
    key = str[0..-2]
    return @tree[key]&.dig(:__leaf__) == true
  end

  if @tree.key?(str)
    self.class.new_from_subtree(@tree[str])
  else
    # return empty node instead of raising
    self.class.new([])
  end
end

Instance Attribute Details

#valuesObject

Returns the value of attribute values.



6
7
8
# File 'lib/yiffspace/auth/permissions.rb', line 6

def values
  @values
end

Class Method Details

.leaves_from_tree(node, prefix = "") ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/yiffspace/auth/permissions.rb', line 72

def self.leaves_from_tree(node, prefix = "")
  result = []
  node.each do |key, subtree|
    next if key == :__leaf__

    path = prefix.empty? ? key : "#{prefix}.#{key}"
    result << path if subtree[:__leaf__]
    result.concat(leaves_from_tree(subtree, path))
  end
  result
end

.new_from_subtree(tree) ⇒ Object



65
66
67
68
69
70
# File 'lib/yiffspace/auth/permissions.rb', line 65

def self.new_from_subtree(tree)
  obj = allocate
  obj.instance_variable_set(:@tree, tree)
  obj.instance_variable_set(:@values, leaves_from_tree(tree))
  obj
end

Instance Method Details

#has?(perm) ⇒ Boolean Also known as: include?

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/yiffspace/auth/permissions.rb', line 30

def has?(perm)
  current = @tree
  parts   = perm.split(".")

  parts.each do |part|
    return false unless current[part]

    current = current[part]
  end

  current[:__leaf__] == true
end

#respond_to_missing?(_name, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/yiffspace/auth/permissions.rb', line 61

def respond_to_missing?(_name, _include_private = false)
  true
end