Mathieu Mathieu - 1 year ago 81
Ruby Question

Factorize ruby script based on Constant Array Loop

In my Ruby on Rails 4 (ruby 2.2) app, i have inside a view:

<%= sanitize( @template.render(
'text1' => modal['text1'],
'text2' => modal['text2'],
'text3' => modal['text3'],
'text4' => modal['text4'],
'image1' => modal['image1'],
'image2' => modal['image2'],
'image3' => modal['image3']
goes on like this....
) %>

Where you see above 'goes on like this', it's because I woukd like to factorize this and use dirctly values coming from this constant:

MODAL_ELEMENTS = [ "text1",

I want to find a way to change what's inside sanitize @template.render so that ruby loops through each of the MODAL_ELEMENTS items (text1, text2,..) and inject them like 'text1' => 'text1' => modal['text1'], 'text2' => modal['text1'] on the code above.

Today I have this but it fails:

<%= sanitize( @template.render(
MODAL_ELEMENTS.each { |element| element => modal[ element ] ) ) %>

The difficulty also is that the loop has to add each coma (",") that we see here in bold:

'text1' => modal['text1'],

'text2' => modal['text2'],


Answer Source

If it is just that string you want and that string is evaluated later then this code would do{ |element| "'#{element}' => modal[ '#{element}' ]"}.join(", ")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download