Module: Challah::Rolls::User::InstanceMethods

Defined in:
lib/challah/rolls/user.rb

Overview

Instance methods to be included once authable_user is set up.

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object

Allow dynamic checking for permissions

admin? is shorthand for:

def admin?
  has(:admin)
end


154
155
156
157
# File 'lib/challah/rolls/user.rb', line 154

def method_missing(sym, *args, &block)
  return has(sym.to_s.gsub(/\?/, '')) if sym.to_s =~ /^[a-z_]*\?$/
  super(sym, *args, &block)
end

Instance Method Details

#default_pathObject

The default url where this user should be redirected to after logging in. Also can be used as the main link at the top of navigation.



86
87
88
# File 'lib/challah/rolls/user.rb', line 86

def default_path
  role ? role.default_path : '/'
end

#has(permission_key) ⇒ Object Also known as: permission?

Returns true if this user has permission to the provided permission key



121
122
123
# File 'lib/challah/rolls/user.rb', line 121

def has(permission_key)
  self.permission_keys.include?(permission_key.to_s)
end

#permission_keysObject

Returns the permission keys in an array for exactly what this user can access. This includes all role based permission keys, and any specifically given to this user through permissions_users



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/challah/rolls/user.rb', line 93

def permission_keys
  return @permission_keys if @permission_keys

  role_keys = if role(true)
    role_key = "#{role.cache_key}/permissions"

    keys = Rails.cache.fetch(role_key) do
      role.permission_keys.clone
    end

    Rails.cache.write(role_key, keys)
    keys
  else
    []
  end

  user_keys = Rails.cache.fetch(permissions_cache_key) do
    user_permission_keys.clone
  end

  user_keys = [] unless user_keys

  Rails.cache.write(permissions_cache_key, keys) unless new_record?

  @permission_keys = (role_keys + user_keys).uniq
end

#permission_keys=(value) ⇒ Object

Set the permission keys that this role can access



127
128
129
130
131
132
# File 'lib/challah/rolls/user.rb', line 127

def permission_keys=(value)
  Rails.cache.delete(permissions_cache_key)

  @permission_keys = value
  @permission_keys
end

#role_id=(value) ⇒ Object

When a role is set, reset the permission_keys



135
136
137
138
139
140
# File 'lib/challah/rolls/user.rb', line 135

def role_id=(value)
  @permission_keys = nil
  @user_permission_keys = nil

  self[:role_id] = value
end

#user_permission_keysObject

Returns the permission keys used by this specific user, does not include any role-based permissions.



143
144
145
# File 'lib/challah/rolls/user.rb', line 143

def user_permission_keys
  new_record? ? [] : self.permissions(true).collect(&:key)
end