Class: HaveAPI::ModelAdapters::ActiveRecord::Input
Class Method Summary
collapse
#[], #has_param?, #initialize, used_by
Class Method Details
.clean(model, raw, extra) ⇒ Object
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
|
# File 'lib/haveapi/model_adapters/active_record.rb', line 144
def self.clean(model, raw, )
return nil if raw.nil?
original = raw
if raw.is_a?(String)
stripped = raw.strip
raise HaveAPI::ValidationError, "not a valid id #{original.inspect}" if stripped.empty?
raw = stripped
elsif [true, false].include?(raw)
raise HaveAPI::ValidationError, "not a valid id #{original.inspect}"
end
value = if integer_pk?(model)
id = coerce_integer_id(raw, original)
raise HaveAPI::ValidationError, "not a valid id #{original.inspect}" if id < 0
id
else
raw
end
if [:fetch]
model.instance_exec(value, &[:fetch])
else
model.find(value)
end
rescue ::ActiveRecord::RecordNotFound
raise HaveAPI::ValidationError, 'resource not found'
rescue ArgumentError, TypeError
raise HaveAPI::ValidationError, "not a valid id #{original.inspect}"
end
|
.coerce_integer_id(raw, original) ⇒ Object
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
|
# File 'lib/haveapi/model_adapters/active_record.rb', line 188
def self.coerce_integer_id(raw, original)
case raw
when Integer
raw
when Float
unless raw.finite? && (raw % 1) == 0
raise HaveAPI::ValidationError, "not a valid id #{original.inspect}"
end
raw.to_i
when String
s = raw.strip
if s.empty? || !s.match?(/\A[+-]?\d+\z/)
raise HaveAPI::ValidationError, "not a valid id #{original.inspect}"
end
Integer(s, 10)
else
raise HaveAPI::ValidationError, "not a valid id #{original.inspect}"
end
end
|
.integer_pk?(model) ⇒ Boolean
179
180
181
182
183
184
185
186
|
# File 'lib/haveapi/model_adapters/active_record.rb', line 179
def self.integer_pk?(model)
pk = model.primary_key
return false unless pk.is_a?(String)
return false unless model.respond_to?(:type_for_attribute)
pk_type = model.type_for_attribute(pk).type
%i[integer bigint].include?(pk_type)
end
|