Class: AuthScope

Inherits:
Object
  • Object
show all
Defined in:
lib/auth_scope.rb,
lib/auth_scope/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(*scopes) ⇒ AuthScope

Returns a new instance of AuthScope.



2
3
4
5
# File 'lib/auth_scope.rb', line 2

def initialize(*scopes)
  @tree = {}
  scopes.join(" ").split(" ").each{|s| add(s) }
end

Instance Method Details

#add(scope_string) ⇒ Object



7
8
9
10
11
12
13
14
15
# File 'lib/auth_scope.rb', line 7

def add(scope_string)
  roots = [@tree]
  
  scope_string.split(":").each do |parts|
    roots = parts.split(",").map do |part|
      roots.map{|r| r[part.to_s] ||= {}; r[part.to_s]}
    end.flatten
  end
end

#all?(*scopes) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
# File 'lib/auth_scope.rb', line 39

def all?(*scopes)
  scopes = scopes.join(" ").split(" ")
  scopes.each{|scope| return false unless can?(scope) }
  true
end

#any?(*scopes) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
37
# File 'lib/auth_scope.rb', line 34

def any?(*scopes)
  scopes = scopes.join(" ").split(" ")
  !!scopes.detect{|scope| can?(scope)}
end

#can?(*args) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/auth_scope.rb', line 17

def can?(*args)
  subject = subject.respond_to?(:to_scope) ? subject.to_scope : subject.to_s
  parts = args.map{|arg| (arg.respond_to?(:to_scope) ? arg.to_scope : arg.to_s).split(":") }.flatten.map(&:to_s)
  roots = [@tree]
  parts.each do |part|
    return true if roots.detect{|r| r.key?('**')}
    is_last = part == parts.last
    if roots.detect{|r| r.key?('*')}
      roots = roots.map{|r| [r[part], r['*']].compact }.flatten
    else
      return false unless roots.detect{|r| r.key?(part)}
      roots = roots.map{|r| r[part] }.flatten
    end
  end
  true
end