Module: Sinatra::HasScope

Defined in:
lib/sinatra/has_scope.rb,
lib/sinatra/has_scope/version.rb

Defined Under Namespace

Modules: Helpers

Constant Summary collapse

TRUE_VALUES =
["true", true, "1", 1]
ALLOWED_TYPES =
{
  :array    => [ Array ],
  :hash     => [ Hash ],
  :boolean  => [ Object ],
  :default  => [ String, Numeric ]
}
VERSION =
"0.1.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#scopes_configurationObject

Returns the value of attribute scopes_configuration.



14
15
16
# File 'lib/sinatra/has_scope.rb', line 14

def scopes_configuration
  @scopes_configuration
end

Class Method Details

.registered(base) ⇒ Object



16
17
18
19
# File 'lib/sinatra/has_scope.rb', line 16

def self.registered(base)
  base.scopes_configuration = { }
  base.helpers HasScope::Helpers
end

Instance Method Details

#has_scope(scope_group, *scopes) ⇒ Object

Detects params from url and apply as scopes to your classes.

Options

  • :type - Checks the type of the parameter sent. If set to :boolean

it just calls the named scope, without any argument. By default, it does not allow hashes or arrays to be given, except if type :hash or :array are set.

  • :as - The key in the params hash expected to find the scope.

Defaults to the scope name.

  • :using - If type is a hash, you can provide :using to convert the hash to

a named scope call with several arguments.

  • :if - Specifies a method, proc or string to call to determine

if the scope should apply

  • :unless - Specifies a method, proc or string to call to determine

if the scope should NOT apply.

  • :default - Default value for the scope. Whenever supplied the scope

is always called.

  • :allow_blank - Blank values are not sent to scopes by default. Set to true to overwrite.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/sinatra/has_scope.rb', line 47

def has_scope(scope_group, *scopes)
  options = scopes.extract_options!
  options.symbolize_keys!
  options.assert_valid_keys(:type, :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] = [*options[:using]]
  end

  self.scopes_configuration ||= {}
  self.scopes_configuration[scope_group] ||= {}

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