Sha256: 5e0f06208b627142dcaf3afe7e1de2a1590dff0f9d76768b072474bab7cb8ef6

Contents?: true

Size: 1.93 KB

Versions: 3

Compression:

Stored size: 1.93 KB

Contents

class AccessControlEntry < ActiveRecord::Base
  belongs_to :user
  belongs_to :role

  scope :by_resource, lambda {|resource_class_name, resource_id|
    where(:resource_class_name=>resource_class_name).
    where(:resource_id=>resource_id)
  }

  def resource
    @resource ||= (resource_id.nil? ? self.resource_class_name.constantize :
                  self.resource_class_name.constantize.find(self.resource_id))
  end

  def resource=(res)
    @resource = res
    if res.type==Class
      self.resource_id = nil
      self.resource_class_name = res.name
    else
      self.resource_id = res.id
      self.resource_class_name = res.class.name
    end
  end

  def options
    @options ||= eval(self.serialized_options)
  end

  def options=(opts)
    raise "I only take hash" unless opts.class==Hash
    klasses = %w(String Symbol)
    opts.delete_if{|u,v| !klasses.include?(u.class.name) || !klasses.include?(v.class.name)}
    @options = opts
    self.serialized_options = opts.inspect
  end

  def configure(ability)
    ability.send method_name, verb, resource, options
  end

  def self.can(verb, resource, options={})
    AccessControlEntry.new(true, verb, resource, options )
  end
  def self.cannot(verb, resource, options)
    AccessControlEntry.new(false, verb, resource, options )
  end

  def initialize(can, verb, resource, options={})
    @options = options
    self.can = can
    self.verb = verb
    self.resource = resource
    self.options = options
  end

  def method_name
    self.can ? :can : :cannot
  end

  def user_email
    self.user.email if self.user
  end
  def user_email=(email)
    self.user = User.find_by_email(email) unless email.blank?
  end

  def role=(role)
    if role.kind_of? Role
      self.role_id = role.id
    else
      role = role.to_s.camelize
      if role.is_numeric?
        self.role_id= role
      else
        self.role_id= Role.find_by_name(role).id
      end
    end
  end

  attr_protected :serialized_options

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
wheels-0.0.21 app/models/access_control_entry.rb
wheels-0.0.20 app/models/access_control_entry.rb
wheels-0.0.19 app/models/access_control_entry.rb