3

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!

3
  • Are your variables (outdoors_donation and snowsports_donation) instance variables? Commented Apr 20, 2015 at 22:52
  • 2
    You could keep the values in a hash and use the variable as the key, e.g. donations[action_name]. Commented Apr 20, 2015 at 22:52
  • YES a hash duh... ugh narrow minded ness will be the death of me, THANKS! Commented Apr 20, 2015 at 23:02

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I'm going to go with the hash though because it feels much cleaner to me, but this is great as well!
Yeah, my answer addresses the question but I think the hash approach is probably a better to solution to the actual problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.