Class: Spree::Ability

Inherits:
Object
  • Object
show all
Includes:
CanCan::Ability
Defined in:
app/models/spree/ability.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(user) ⇒ Ability

Returns a new instance of Ability.



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
63
64
65
66
67
68
69
70
71
72
# File 'app/models/spree/ability.rb', line 25

def initialize(user)
  clear_aliased_actions

  # override cancan default aliasing (we don't want to differentiate between read and index)
  alias_action :delete, to: :destroy
  alias_action :edit, to: :update
  alias_action :new, to: :create
  alias_action :new_action, to: :create
  alias_action :show, to: :read
  alias_action :index, :read, to: :display
  alias_action :create, :update, :destroy, to: :modify

  user ||= Spree.user_class.new

  if user.respond_to?(:has_spree_role?) && user.has_spree_role?('admin')
    can :manage, :all
  else
    can :display, Country
    can :display, OptionType
    can :display, OptionValue
    can :create, Order
    can :read, Order do |order, token|
      order.user == user || order.guest_token && token == order.guest_token
    end
    can :update, Order do |order, token|
      !order.completed? && (order.user == user || order.guest_token && token == order.guest_token)
    end
    can :display, CreditCard, user_id: user.id
    can :display, Product
    can :display, ProductProperty
    can :display, Property
    can :create, Spree.user_class
    can [:read, :update, :destroy], Spree.user_class, id: user.id
    can :display, State
    can :display, Taxon
    can :display, Taxonomy
    can :display, Variant
    can :display, Zone
  end

  # Include any abilities registered by extensions, etc.
  Ability.abilities.merge(abilities_to_register).each do |clazz|
    merge clazz.new(user)
  end

  # Protect admin role
  cannot [:update, :destroy], Role, name: ['admin']
end

Class Method Details

.register_ability(ability) ⇒ Object

Allows us to go beyond the standard cancan initialize method which makes it difficult for engines to modify the default Ability of an application. The ability argument must be a class that includes the CanCan::Ability module. The registered ability should behave properly as a stand-alone class and therefore should be easy to test in isolation.



17
18
19
# File 'app/models/spree/ability.rb', line 17

def self.register_ability(ability)
  abilities.add(ability)
end

.remove_ability(ability) ⇒ Object



21
22
23
# File 'app/models/spree/ability.rb', line 21

def self.remove_ability(ability)
  abilities.delete(ability)
end