module IAmICan::Permission

Public Instance Methods

deconstruct_obj(obj) click to toggle source
# File lib/i_am_i_can/permission.rb, line 30
def deconstruct_obj(obj)
  return { } unless obj

  if obj.is_a?(String) || obj.is_a?(Symbol)
    { obj_type: obj }
  elsif obj.respond_to?(:attributes)
    { obj_type: obj.class.name, obj_id: obj.id }
  else
    { obj_type: obj.to_s, obj_id: nil }
  end
end
matched(actions, obj) click to toggle source
# File lib/i_am_i_can/permission.rb, line 11
def matched(actions, obj)
  _ = deconstruct_obj(obj)
  where(action: actions,
        obj_type: [nil, _[:obj_type]],
        obj_id: [nil, _[:obj_id]])
end
matched?(actions, obj) click to toggle source
# File lib/i_am_i_can/permission.rb, line 18
def matched?(actions, obj)
  matched(actions, obj).present?
end
matched_all?(actions, obj) click to toggle source
# File lib/i_am_i_can/permission.rb, line 22
def matched_all?(actions, obj)
  matched(actions, obj).count == Array(actions).count
end
name() click to toggle source

like: manage_User_1

# File lib/i_am_i_can/permission.rb, line 49
def name
  [action, obj_type, obj_id].compact.join('_').to_sym
end
names() click to toggle source
# File lib/i_am_i_can/permission.rb, line 42
def names
  all.map(&:name)
end
obj() click to toggle source

returns :user, User, user

# File lib/i_am_i_can/permission.rb, line 57
def obj
  return if obj_type.blank?
  return obj_type.constantize.find(obj_id) if obj_id.present?
  obj_type[/[A-Z]/] ? obj_type.constantize : obj_type.to_sym
end
which(action:, obj: nil, **conditions) click to toggle source
# File lib/i_am_i_can/permission.rb, line 26
def which(action:, obj: nil, **conditions)
  find_by!(action: action, **deconstruct_obj(obj), **conditions)
end