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



144
145
146
147
# File 'lib/grape/validations.rb', line 144

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

#group(element, &block) ⇒ Object



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

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

#optional(*attrs, &block) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
# File 'lib/grape/validations.rb', line 122

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

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

  push_declared_params(attrs)
  validates(attrs, validations)
end

#params(params) ⇒ Object



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

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
119
120
# File 'lib/grape/validations.rb', line 110

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

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

  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