Module: Volt::Model::Permissions::ClassMethods

Defined in:
lib/volt/models/permissions.rb

Instance Method Summary collapse

Instance Method Details

#own_by_user(key = :user_id) ⇒ Object

Own by user requires a logged in user (Volt.current_user) to save a model. If the user is not logged in, an validation error will occur. Once created the user can not be changed.

Parameters:

  • key (Symbol) (defaults to: :user_id)

    the name of the attribute to store



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/volt/models/permissions.rb', line 12

def own_by_user(key=:user_id)
  # When the model is created, assign it the user_id (if the user is logged in)
  on(:new) do
    # Only assign the user_id if there isn't already one and the user is logged in.
    if _user_id.nil? && !(user_id = Volt.current_user_id).nil?
      send(:"_#{key}=", user_id)
    end
  end

  on(:create, :update) do
    # Don't allow the key to be changed
    deny(key)
  end

  # Setup a validation that requires a user_id
  validate do
    # Lookup directly in @attributes to optimize and prevent the need
    # for a nil model.
    unless @attributes[:user_id]
      # Show an error that the user is not logged in
      next {key => ['requires a logged in user']}
    end
  end
end

#permissions(*actions, &block) ⇒ Object

permissions takes a block and yields



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/volt/models/permissions.rb', line 48

def permissions(*actions, &block)
  # Store the permissions block so we can run it in validations
  self.__permissions__ ||= {}

  # if no action was specified, assume all actions
  actions += [:create, :read, :update, :delete] if actions.size == 0

  actions.each do |action|
    # Add to an array of proc's for each action
    (self.__permissions__[action] ||= []) << block
  end

  validate do
    action = new? ? :create : :update
    run_permissions(action)
  end
end