Class: GrantFront::Policy

Inherits:
Object
  • Object
show all
Defined in:
lib/grant-front/policy.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Policy

Returns a new instance of Policy.



61
62
63
64
65
66
# File 'lib/grant-front/policy.rb', line 61

def initialize(klass)
  @klass = klass.to_s
  @name = @klass.gsub(/Policy$/, '')
  @methods = {}
  @roles = []
end

Instance Attribute Details

#klassObject

Returns the value of attribute klass.



3
4
5
# File 'lib/grant-front/policy.rb', line 3

def klass
  @klass
end

#methodsObject

Returns the value of attribute methods.



3
4
5
# File 'lib/grant-front/policy.rb', line 3

def methods
  @methods
end

#nameObject

Returns the value of attribute name.



3
4
5
# File 'lib/grant-front/policy.rb', line 3

def name
  @name
end

#rolesObject

Returns the value of attribute roles.



3
4
5
# File 'lib/grant-front/policy.rb', line 3

def roles
  @roles
end

Class Method Details

.all(options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/grant-front/policy.rb', line 6

def all(options={})
  options[:rake] = true if options[:rake].nil?

  if defined? Rails
    policies_path = Rails.root.join('app/policies/').to_s
    policie_path = Rails.root.join(policies_path, '**/*.rb').to_s
    constants = Dir.glob(policie_path).inject([]) do |arr, item|
      require item if options[:rake]
      klass = item.gsub(policies_path, '').gsub('.rb', '').camelcase
      arr << self.new(klass) unless klass == 'ApplicationPolicy'
      arr
    end
  end

  if options[:rake]
    constants = Object.constants.inject([]) do |arr, name|
      unless name == :Config
        klass = Object.const_get(name)
        if klass.class == Class && klass.superclass == ApplicationPolicy
          arr << self.new(klass)
        end
      end
      arr
    end
  end

  constants
end

.find(klass) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/grant-front/policy.rb', line 35

def find(klass)
  policy = self.new(klass.to_s)
  klass = Object.const_get(klass.to_s)
  reg = Regexp.new(/\?$/)
  user = Struct.new(:id, :roles).new(1, [])

  klass.mock!
  klass_policy = klass.new(user, user)
  klass_policy.methods.each do |name|
    if name =~ reg
      owner = klass_policy.method(name).owner
      if owner == klass or owner == ApplicationPolicy
        roles = klass_policy.send(name)
        roles ||= []
        policy.methods[name.to_s.gsub(reg, '').to_sym] = roles
        policy.roles += roles
      end
    end
  end
  klass.unmock!

  policy.roles.uniq!
  policy
end

Instance Method Details

#urnObject



68
69
70
# File 'lib/grant-front/policy.rb', line 68

def urn
  self.name.downcase
end