Skip to content

Commit

Permalink
Adjust validation - lookup strings immediately, in case of instance p…
Browse files Browse the repository at this point in the history
…aram
  • Loading branch information
nimmolo committed Jan 28, 2025
1 parent 66dbd64 commit 8a4870b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 17 deletions.
23 changes: 10 additions & 13 deletions app/classes/query/modules/validation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,7 @@ def validate_record_or_id_or_string(arg, val, type = ActiveRecord::Base)
elsif could_be_record_id?(val)
val.to_i
elsif val.is_a?(String)
lookup = "Lookup::#{type.name.pluralize}"
lookup = lookup.constantize
result = lookup.new(val).ids&.first
raise("Couldn't find an id for : #{val.inspect}") unless result

result
lookup_record_by_name(type, val).id
else
raise("Value for :#{arg} should be id, string or an #{type} instance, " \
"got: #{val.inspect}")
Expand Down Expand Up @@ -267,16 +262,10 @@ def validate_query(arg, val)

def find_cached_parameter_instance(model, arg)
@params_cache ||= {}
# unless could_be_record_id?(arg)
# raise("Value for :#{arg} is not an id, got #{val.inspect}")
# end
# @params_cache[arg] ||= model.find(params[arg])
@params_cache[arg] ||= if could_be_record_id?(params[arg])
model.find(params[arg])
else
lookup = "Lookup::#{model.name.pluralize}"
lookup = lookup.constantize
lookup.new(params[arg]).instances.first
lookup_record_by_name(model, params[arg])
end
end

Expand All @@ -299,4 +288,12 @@ def could_be_record_id?(val)
# (blasted admin user has id = 0!)
val.is_a?(String) && (val == "0") && (arg == :user)
end

def lookup_record_by_name(type, val)
lookup = "Lookup::#{type.name.pluralize}".constantize
result = lookup.new(val).instances&.first
raise("Couldn't find an id for : #{val.inspect}") unless result

result
end
end
7 changes: 3 additions & 4 deletions test/classes/query_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,16 @@ def test_validate_params_instances_by_user

# assert_raises(RuntimeError) { Query.lookup(:Image) }
assert_raises(RuntimeError) { Query.lookup(:Image, by_user: :bogus) }
# assert_raises(RuntimeError) { Query.lookup(:Image, by_user: "rolf") }
assert_raises(RuntimeError) { Query.lookup(:Image, by_user: "foo") }
assert_raises(RuntimeError) { Query.lookup(:Image, by_user: @fungi) }
assert_equal(rolf.id,
Query.lookup(:Image, by_user: rolf).params[:by_user])
assert_equal(rolf.id,
Query.lookup(:Image, by_user: rolf.id).params[:by_user])
assert_equal(rolf.id,
Query.lookup(:Image, by_user: rolf.id.to_s).
params[:by_user])
Query.lookup(:Image, by_user: rolf.id.to_s).params[:by_user])
assert_equal(rolf.id,
Query.lookup(:Image, by_user: rolf.login).params[:by_user])
Query.lookup(:Image, by_user: "rolf").params[:by_user])
end

def test_validate_params_instances_users
Expand Down

0 comments on commit 8a4870b

Please sign in to comment.