2019-07-30 21:29:24 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-06-12 20:03:43 +00:00
|
|
|
# License: AGPL-3.0-or-later WITH WTO-AP-3.0-or-later
|
|
|
|
# Full license explanation at https://github.com/houdiniproject/houdini/blob/master/LICENSE
|
2018-03-25 17:30:42 +00:00
|
|
|
module RetrieveActiveRecordItems
|
2019-07-30 21:29:24 +00:00
|
|
|
def self.retrieve(data, optional = false)
|
|
|
|
data.map do |k, v|
|
|
|
|
our_integer = begin
|
|
|
|
Integer(v)
|
|
|
|
rescue StandardError
|
|
|
|
nil
|
|
|
|
end
|
2018-03-25 17:30:42 +00:00
|
|
|
unless (optional && v.nil?) || (our_integer && our_integer > 0)
|
2019-07-30 21:29:24 +00:00
|
|
|
raise ArgumentError, "Value '#{v}' for Key '#{k}' is not valid"
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
|
|
|
|
2019-07-30 21:29:24 +00:00
|
|
|
raise ArgumentError, "Key '#{k}' is not a class" unless k.is_a? Class
|
|
|
|
|
2018-03-25 17:30:42 +00:00
|
|
|
ret = []
|
|
|
|
if optional && v.nil?
|
|
|
|
ret = [k, nil]
|
|
|
|
else
|
|
|
|
ret = [k, k.where('id = ?', our_integer).first]
|
2019-07-30 21:29:24 +00:00
|
|
|
if ret[1].nil?
|
|
|
|
raise ParamValidation::ValidationError.new("ID #{v} is not a valid #{k}", key: k)
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
ret
|
2019-07-30 21:29:24 +00:00
|
|
|
end.to_h
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
|
|
|
|
2019-07-30 21:29:24 +00:00
|
|
|
def self.retrieve_from_keys(input, class_to_key_hash, optional = false)
|
|
|
|
class_to_key_hash.map do |k, v|
|
|
|
|
raise ArgumentError, "Key '#{k}' is not a class" unless k.is_a? Class
|
|
|
|
|
2018-03-25 17:30:42 +00:00
|
|
|
ret = nil
|
|
|
|
begin
|
2019-07-30 21:29:24 +00:00
|
|
|
item = retrieve({ k => input[v] }, optional)
|
2018-03-25 17:30:42 +00:00
|
|
|
ret = [v, item[k]]
|
|
|
|
rescue ParamValidation::ValidationError
|
2019-07-30 21:29:24 +00:00
|
|
|
raise ParamValidation::ValidationError.new("ID #{input[v]} is not a valid #{k}", key: v)
|
2018-03-25 17:30:42 +00:00
|
|
|
rescue ArgumentError
|
2019-07-30 21:29:24 +00:00
|
|
|
raise ParamValidation::ValidationError.new("#{input[v]} is not a valid ID for Key '#{v}'", key: v)
|
|
|
|
rescue StandardError
|
|
|
|
raise ParamValidation::ValidationError.new("#{input[v]} is not a valid ID for Key '#{v}'", key: v)
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
|
|
|
ret
|
2019-07-30 21:29:24 +00:00
|
|
|
end.to_h
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
2019-07-30 21:29:24 +00:00
|
|
|
end
|