module GrapeHasScope

Constants

ALLOWED_TYPES
TRUE_VALUES

Public Class Methods

included(base) click to toggle source
# File lib/grape_has_scope.rb, line 11
def self.included(base)
  base.class_eval do
    attr_accessor :scopes_configuration
  end
end

Public Instance Methods

apply_scopes(target, hash=params) click to toggle source

Receives an object where scopes will be applied to.

class GraduationsController < InheritedResources::Base
  has_scope :featured, :type => true, :only => :index
  has_scope :by_degree, :only => :index

  def index
    @graduations = apply_scopes(Graduation).all
  end
end
# File lib/grape_has_scope.rb, line 54
def apply_scopes(target, hash=params)
  return target unless scopes_configuration

  @scopes_configuration.each do |scope, options|
    next unless apply_scope_to_action?(options)
    key = options[:as]

    if hash.key?(key)
      value, call_scope = hash[key], true
    elsif options.key?(:default)
      value, call_scope = options[:default], true
      value = value.call(self) if value.is_a?(Proc)
    end

    value = parse_value(options[:type], key, value)
    value = normalize_blanks(value)

    if call_scope && (value.present? || options[:allow_blank])
      current_scopes[key] = value
      target = call_scope_by_type(options[:type], scope, target, value, options)
    end
  end

  target
end
current_scopes() click to toggle source

Returns the scopes used in this action.

# File lib/grape_has_scope.rb, line 143
def current_scopes
  @current_scopes ||= {}
end
has_scope(*scopes, &block) click to toggle source
# File lib/grape_has_scope.rb, line 17
def has_scope(*scopes, &block)
  options = scopes.extract_options!
  options.symbolize_keys!
  options.assert_valid_keys(:type, :only, :except, :if, :unless, :default, :as, :using, :allow_blank)

  if options.key?(:using)
    if options.key?(:type) && options[:type] != :hash
      raise "You cannot use :using with another :type different than :hash"
    else
      options[:type] = :hash
    end

    options[:using] = Array(options[:using])
  end

  options[:only]   = Array(options[:only])
  options[:except] = Array(options[:except])

  @scopes_configuration = (@scopes_configuration || {}).dup

  scopes.each do |scope|
    @scopes_configuration[scope] ||= { :as => scope, :type => :default, :block => block }
    @scopes_configuration[scope] = @scopes_configuration[scope].merge(options)
  end
end