Skip to content

Commit

Permalink
Fix failing spec
Browse files Browse the repository at this point in the history
  • Loading branch information
ellmetha committed Jul 20, 2024
1 parent 373c1b6 commit de40933
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
15 changes: 15 additions & 0 deletions spec/marten/template/value_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,21 @@ describe Marten::Template::Value do
value["test_attr"].should eq Marten::Template::Value.from("hello")
end

it "raises an unknown variable error if the attribute does not exist" do
value = Marten::Template::Value.from({"foo" => "bar", "test" => 42})
expect_raises(Marten::Template::Errors::UnknownVariable) { value["unknown"] }
end

it "raises an unknown variable error if the index does not exist for an array" do
value = Marten::Template::Value.from(["foo", "bar"])
expect_raises(Marten::Template::Errors::UnknownVariable) { value["4"] }
end

it "raises an unknown variable error if the index is not a number for an array" do
value = Marten::Template::Value.from(["foo", "bar"])
expect_raises(Marten::Template::Errors::UnknownVariable) { value["bad"] }
end

it "raises an unknown variable error if the raw object does not allow attribute lookups" do
value = Marten::Template::Value.from(42)
expect_raises(Marten::Template::Errors::UnknownVariable) { value["unknown"] }
Expand Down
11 changes: 9 additions & 2 deletions src/marten/template/value.cr
Original file line number Diff line number Diff line change
Expand Up @@ -93,21 +93,28 @@ module Marten
private def resolve_attribute(key)
object = raw

attempt_attribute_resolution_after_failed_collection_lookup = false

if object.responds_to?(:[]) && !object.is_a?(Array) && !object.is_a?(String) &&
!object.is_a?(Marten::Template::Object)
begin
return object[key.to_s]
rescue KeyError
attempt_attribute_resolution_after_failed_collection_lookup = true
end
elsif object.is_a?(Indexable) && !object.is_a?(Marten::Template::Object) && key.responds_to?(:to_i)
begin
return object[key.to_i]
rescue ArgumentError | IndexError
attempt_attribute_resolution_after_failed_collection_lookup = true
end
elsif object.responds_to?(:resolve_template_attribute)
return object.resolve_template_attribute(key.to_s)
end

if object.responds_to?(:resolve_template_attribute)
return object.resolve_template_attribute(key.to_s)
if attempt_attribute_resolution_after_failed_collection_lookup
res = object.responds_to?(:resolve_template_attribute) ? object.resolve_template_attribute(key.to_s) : nil
return res if !res.nil?
end

raise Errors::UnknownVariable.new
Expand Down

0 comments on commit de40933

Please sign in to comment.