Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby interpolating into variable

This is a hard question for me to even ask so I'll share the code first:

        <div class="col-xs-12">
          We operate on a pay what you want model. Keep in mind that 
          <% if action_name == "outdoors" %>
            <%= outdoors_donation.html_safe %>
          <% elsif action_name == "snowsports" %>
            <%= snowsports_donation.html_safe %>
          <% end %>
          Below, you'll find information on how we calculated your order's suggested donation of $<span id="modal-sentence"></span>.
        </div>

Rather than the clunky if statement, I'd rather just be able to inject action_name directly into the variable that's being called.... something like

<%= "#{action_name}_donation".html_safe %>

But not sure what this would actually be

Thanks!

like image 808
james Avatar asked Jun 03 '26 12:06

james


1 Answers

You can use send in ruby to send a method that you provide the name for. This allows you to do interpolation:

<%= self.send("#{action_name}_donation").html_safe %>

In this context self would be the view instance which is the same as calling outdoors_donation.html_safe or snowsports_donation.html_safe or whatever.

like image 98
Shadwell Avatar answered Jun 06 '26 03:06

Shadwell