Module: Sinatra::HasScope::Helpers

Defined in:
lib/sinatra/has_scope.rb

Instance Method Summary collapse

Instance Method Details

#applicable?(string_proc_or_symbol, expected) ⇒ Boolean

Evaluates the scope options :if or :unless. Returns true if the proc method, or string evals to the expected value.

Returns:

  • (Boolean)


134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/sinatra/has_scope.rb', line 134

def applicable?(string_proc_or_symbol, expected) #:nodoc:
  case string_proc_or_symbol
    when String
      eval(string_proc_or_symbol) == expected
    when Proc
      string_proc_or_symbol.call(self) == expected
    when Symbol
      send(string_proc_or_symbol) == expected
    else
      true
  end
end

#apply_scopes(scope_group, target, hash) ⇒ Object

Receives an object where scopes will be applied to.

has_scope :graduation, :featured, :type => true has_scope :graduation, :by_degree

get ‘/graduations’ do

@graduations = apply_scopes(:graduation, Graduation, params).all

end



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/sinatra/has_scope.rb', line 84

def apply_scopes(scope_group, target, hash)
  return target unless settings.scopes_configuration

  if settings.scopes_configuration.key?(scope_group)
    settings.scopes_configuration[scope_group].each do |scope, options|
      key = options[:as].to_s

      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)

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

  target
end

#call_scope_by_type(type, scope, target, value, options) ⇒ Object

Call the scope taking into account its type.



121
122
123
124
125
126
127
128
129
130
# File 'lib/sinatra/has_scope.rb', line 121

def call_scope_by_type(type, scope, target, value, options) #:nodoc:
  if type == :boolean
    target.send(scope)
  elsif value && options.key?(:using)
    value = value.values_at(*options[:using])
    target.send(scope, *value)
  else
    target.send(scope, value)
  end
end

#parse_value(type, key, value) ⇒ Object

Set the real value for the current scope if type check.



110
111
112
113
114
115
116
117
118
# File 'lib/sinatra/has_scope.rb', line 110

def parse_value(type, key, value) #:nodoc:
  if type == :boolean
    TRUE_VALUES.include?(value)
  elsif value && ALLOWED_TYPES[type].none?{ |klass| value.is_a?(klass) }
    raise "Expected type :#{type} in params[:#{key}], got #{value.class}"
  else
    value
  end
end