module Volt::Model::Permissions::ClassMethods

Public Instance Methods

own_by_user(key = :user_id) click to toggle source

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.

@param key [Symbol] the name of the attribute to store

# 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) click to toggle source

permissions takes a block and yields

# 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