Module: Zuul::ActiveRecord::AuthorizationMethods::ClassMethods

Defined in:
lib/zuul/active_record.rb

Instance Method Summary collapse

Instance Method Details

#auth_scope(scope = nil, *exec_args, &block) ⇒ Object

Return the requested scope, call a method within a scope, or execute an optional block within that scope

If an optional block is passed, it will be executed within the provided scope. This allows you to call methods on the model or the auth scope without having to specify a scope each time. The exec_args hash can be used to pass arguments through to the block.

If a block is not passed, exec_args can be used to provide a method and arguments to be called on the object within the requested scope.

The reason this is defined separately at the class and instance level is because it uses instance_exec to execute the block within the scope of the object (either class or instance) and then uses method_missing temporarily to provide the auth scope methods.



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/zuul/active_record.rb', line 193

def auth_scope(scope=nil, *exec_args, &block)
  scope ||= current_auth_scope
  raise ::Zuul::Exceptions::UndefinedScope unless auth_scopes.has_key?(scope)

  if block_given? || (exec_args.length > 0 && exec_args[0].is_a?(Symbol) && respond_to?(exec_args[0]))
    old_scope = current_auth_scope
    self.current_auth_scope = scope
    
    instance_eval do
      def method_missing (meth,*args)
        return auth_scopes[current_auth_scope].send(meth, *args) if auth_scopes[current_auth_scope].respond_to?(meth)
        raise NoMethodError, "#{self.name}.#{meth} does not exist."
      end
    end
    exec_result = block_given? ? instance_exec(*exec_args, &block) : send(exec_args.slice!(0), *exec_args)
    instance_eval do
      undef method_missing
    end

    self.current_auth_scope = old_scope
    return exec_result
  end

  auth_scopes[scope]
end

#auth_scope_eval(scope = nil, &block) ⇒ Object

Evaluate a block within the requested scope



220
221
222
# File 'lib/zuul/active_record.rb', line 220

def auth_scope_eval(scope=nil, &block)
  auth_scope(scope).instance_eval &block
end

#current_auth_scope=(scope) ⇒ Object

Set the current auth scope

The current_auth_scope is the scope that is currently active on the model for all auth operations



227
228
229
# File 'lib/zuul/active_record.rb', line 227

def current_auth_scope=(scope)
  @current_auth_scope = scope.to_sym
end