Module: Humanity::Base

Defined in:
lib/humanity/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/humanity/base.rb', line 3

def self.included(base)
  base.has_many :assignments, as: :human, dependent: :destroy, class_name: 'Humanity::Assignment'
  base.has_many :roles, through: :assignments, class_name: 'Humanity::Role'

  base.validates_presence_of :username
  base.validates_uniqueness_of :username

  Role.class_eval do
    has_many :humans, through: :assignments, source_type: base.to_s
  end
end

Instance Method Details

#admin?Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/humanity/base.rb', line 27

def admin?
  has_role? :admin
end

#developer?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/humanity/base.rb', line 31

def developer?
  has_role? :developer
end

#has_role?(*role) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/humanity/base.rb', line 23

def has_role?(*role)
  roles.where(name: role.flatten.map(&:to_s)).any?
end

#nameObject



15
16
17
# File 'lib/humanity/base.rb', line 15

def name
  "#{first_name} #{last_name}".strip
end

#role_symbolsObject



19
20
21
# File 'lib/humanity/base.rb', line 19

def role_symbols
  roles.map(&:to_sym)
end

#to_sObject



72
73
74
# File 'lib/humanity/base.rb', line 72

def to_s
  name
end

#update_login_info!Object



65
66
67
68
69
70
# File 'lib/humanity/base.rb', line 65

def 
  self. = 
  self. = Time.now
  self. = .to_i + 1
  self.save
end

#update_roles!(role_names, source) ⇒ 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
59
60
61
62
63
# File 'lib/humanity/base.rb', line 35

def update_roles!(role_names, source)
  source = source.to_s unless source.nil?

  prev_roles = self.roles
  new_roles = if Role.respond_to? :find_or_create_by
    role_names.map { |n| Role.find_or_create_by(name: n) }
  else
    role_names.map { |n| Role.find_or_create_by_name(n) }
  end

  # Create new roles and/or update source
  new_roles.each do |role|
    assignment = if Assignment.respond_to? :find_or_initialize_by
      Assignment.find_or_initialize_by(human_id: self.id, human_type: self.class.to_s, role_id: role.id)
    else
      Assignment.find_or_initialize_by_human_id_and_human_type_and_role_id(self.id, self.class.to_s, role.id)
    end
    assignment.source = source
    assignments << assignment if assignment.changed?
  end

  # Remove roles we had but don't anymore
  old_roles = (prev_roles - new_roles)
  assignments.each do |a|
    a.destroy if old_roles.include?(a.role) && a.source == source
  end

  roles.reload
end