Class: Grape::Validations::ParamsScope

Inherits:
Object
  • Object
show all
Defined in:
lib/grape/validations.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts, &block) ⇒ ParamsScope

Returns a new instance of ParamsScope.


92
93
94
95
96
97
98
99
100
101
102
# File 'lib/grape/validations.rb', line 92

def initialize(opts, &block)
  @element  = opts[:element]
  @parent   = opts[:parent]
  @api      = opts[:api]
  @optional = opts[:optional] || false
  @declared_params = []

  instance_eval(&block)

  configure_declared_params
end

Instance Attribute Details

#elementObject

Returns the value of attribute element


90
91
92
# File 'lib/grape/validations.rb', line 90

def element
  @element
end

#parentObject

Returns the value of attribute parent


90
91
92
# File 'lib/grape/validations.rb', line 90

def parent
  @parent
end

Instance Method Details

#full_name(name) ⇒ Object


140
141
142
143
# File 'lib/grape/validations.rb', line 140

def full_name(name)
  return "#{@parent.full_name(@element)}[#{name}]" if @parent
  name.to_s
end

#group(element, &block) ⇒ Object


130
131
132
# File 'lib/grape/validations.rb', line 130

def group(element, &block)
  requires(element, &block)
end

#optional(*attrs, &block) ⇒ Object


120
121
122
123
124
125
126
127
128
# File 'lib/grape/validations.rb', line 120

def optional(*attrs, &block)
  return new_scope(attrs, true, &block) if block_given?

  validations = {}
  validations.merge!(attrs.pop) if attrs.last.is_a?(Hash)

  push_declared_params(attrs)
  validates(attrs, validations)
end

#params(params) ⇒ Object


134
135
136
137
138
# File 'lib/grape/validations.rb', line 134

def params(params)
  params = @parent.params(params) if @parent
  params = params[@element] || {} if @element
  params
end

#requires(*attrs, &block) ⇒ Object


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

def requires(*attrs, &block)
  return new_scope(attrs, &block) if block_given?

  validations = { presence: true }
  validations.merge!(attrs.pop) if attrs.last.is_a?(Hash)

  push_declared_params(attrs)
  validates(attrs, validations)
end

#should_validate?(parameters) ⇒ Boolean

Returns:

  • (Boolean)

104
105
106
107
108
# File 'lib/grape/validations.rb', line 104

def should_validate?(parameters)
  return false if @optional && params(parameters).blank?
  return true if parent.nil?
  parent.should_validate?(parameters)
end