Module: ActsAsRole::Role::ClassMethods

Defined in:
lib/acts_as_role.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_role(column, options = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/acts_as_role.rb', line 14

def acts_as_role column, options={}

  options.symbolize_keys!

  define_method "setup_roles_for_#{column}" do
    self.setup_roles self.send(column), options, column
  end

  define_method "save_roles" do
    self.send("#{column}=",@rolez.join("_")) if @rolez
  end

  options[:values].each do |role|
    define_method "is_#{role}?" do
      @rolez && @rolez.include?(role.to_sym)
    end
  end

  define_method "add_#{column.to_s.pluralize}" do |*roles|          
    roles.each {|x| @rolez << x if not @rolez.include?(x) }
    save_roles
  end  

  define_method "remove_#{column.to_s.pluralize}" do |*roles|
    roles.each {|x| @rolez.delete(x) }
    save_roles
  end

  define_method "has_#{column.to_s.pluralize}?" do |*roles|
    @rolez && roles.flatten.map { |r| r.to_sym }.all? { |r| @rolez.include?(r) }
  end

  define_method "has_#{column.to_s.singularize}?" do |role|
    @rolez && @rolez.include?(role)
  end

  define_method "list_#{column.to_s.pluralize}" do 
    @rolez
  end

  define_method "available_#{column.to_s.pluralize}" do 
    "#{options[:values].to_a}"
  end

  after_initialize "setup_roles_for_#{column}".to_sym

  validates "#{column}".to_sym, :roles => { :roles => options[:values], :message => options[:message] }

end