Class: RailsParam::ParamEvaluator

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_param/param_evaluator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params, context = nil) ⇒ ParamEvaluator

Returns a new instance of ParamEvaluator.



5
6
7
8
# File 'lib/rails_param/param_evaluator.rb', line 5

def initialize(params, context = nil)
  @params = params
  @context = context
end

Instance Attribute Details

#paramsObject

Returns the value of attribute params.



3
4
5
# File 'lib/rails_param/param_evaluator.rb', line 3

def params
  @params
end

Instance Method Details

#param!(name, type, options = {}, &block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rails_param/param_evaluator.rb', line 10

def param!(name, type, options = {}, &block)
  name = name.is_a?(Integer)? name : name.to_s
  return unless params.include?(name) || check_param_presence?(options[:default]) || options[:required]

  parameter_name = @context ? "#{@context}[#{name}]" : name
  coerced_value = coerce(parameter_name, params[name], type, options)

  parameter = RailsParam::Parameter.new(
    name: parameter_name,
    value: coerced_value,
    type: type,
    options: options,
    &block
  )

  parameter.set_default if parameter.should_set_default?

  # validate presence
  if params[name].nil? && options[:required]
    raise InvalidParameterError.new(
      "Parameter #{parameter_name} is required",
      param: parameter_name,
      options: options
    )
  end

  recurse_on_parameter(parameter, &block) if block_given?

  # apply transformation
  parameter.transform if options[:transform]

  # validate
  validate!(parameter)

  # set params value
  params[name] = parameter.value
end