" c = {"id" => "això és una merda <%=rand(1..10)%>"} If you run ERB.new(a).result," /> " c = {"id" => "això és una merda <%=rand(1..10)%>"} If you run ERB.new(a).result," /> " c = {"id" => "això és una merda <%=rand(1..10)%>"} If you run ERB.new(a).result,"/>

When using a Hash as a ERB templates, ruby complains about "encoding"

52 Views Asked by At

Simply to that

require 'erb'
a = "això és una merda <%=rand(1..20)%>"
c = {"id" => "això és una merda <%=rand(1..10)%>"}

If you run ERB.new(a).result, then all is fine:

ERB.new(a).result
=> "això és una merda 3"

But with ERB.new(c).result ruby complains of encoding:

ERB.new(c).result
/usr/lib/ruby/3.0.0/erb/compiler.rb:315:in `compile': undefined method `encoding' for {"id"=>"això és una merda <%=rand(1..10)%>"}:Hash (NoMethodError)
        from /usr/lib/ruby/3.0.0/erb.rb:351:in `initialize'
        from (irb):57:in `new'
        from (irb):57:in `<main>'
        from /usr/lib/ruby/gems/3.0.0/gems/irb-1.4.2/exe/irb:11:in `<top (required)>'
        from /usr/bin/irb:25:in `load'
        from /usr/bin/irb:25:in `<main>'

My expected result were:

{"id" => "això és una merda 3"}

I could cast c as string, but I want as Hash.

1

There are 1 best solutions below

4
Stefan On

ERB works solely on strings. If you have a structure containing strings like an array of string or a hash with string keys or values, you have to process the strings yourself individually.

To process your hash values, you could use transform_values! which passes each value to a block and updates the value with the block's result:

require 'erb'

c = {"id" => "això és una merda <%=rand(1..10)%>"}

c.transform_values! { |str| ERB.new(str).result }

c #=> {"id"=>"això és una merda 7"}

(there's also a non-! variant which returns a new hash without modifying the receiver)