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



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

def own_by_user(key = :user_id)
  relation, pattern = key.to_s, /_id$/
  if relation.match(pattern)
    belongs_to key.to_s.gsub(pattern, '')
  else
    raise "You tried to auto associate a model using #{key}, but #{key} "\
          "does not end in `_id`"
  end          # 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 get(:user_id).nil? && !(user_id = Volt.current_user_id).nil?
      set(key, user_id)
    end
  end

  permissions(: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



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/volt/models/permissions.rb', line 43

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