Ruby templates: How to pass variables into inlined ERB?

For a simple solution, use OpenStruct: require ‘erb’ require ‘ostruct’ namespace = OpenStruct.new(name: ‘Joan’, last: ‘Maragall’) template=”Name: <%= name %> <%= last %>” result = ERB.new(template).result(namespace.instance_eval { binding }) #=> Name: Joan Maragall The code above is simple enough but has (at least) two problems: 1) Since it relies on OpenStruct, an access to a … Read more

raw vs. html_safe vs. h to unescape html

I think it bears repeating: html_safe does not HTML-escape your string. In fact, it will prevent your string from being escaped. <%= “<script>alert(‘Hello!’)</script>” %> will put: &lt;script&gt;alert(&#x27;Hello!&#x27;)&lt;/script&gt; into your HTML source (yay, so safe!), while: <%= “<script>alert(‘Hello!’)</script>”.html_safe %> will pop up the alert dialog (are you sure that’s what you want?). So you probably don’t … Read more

tech