0

I have multiple if statements.

  <% if offer.merchant == 'webgains' %>
    <a href="<%= offer.url %>&clickref=<%= current_user.id %>" target="_blank">
  <% else %>
    <a href="<%= offer.url %>" target="_blank">
  <% end %>

  <% if offer.merchant == 'rakuten' %>
    <h1>WOOP</h1>
  <% else %>
    <h1>FAIL</h1>
  <% end %>

  <% if offer.merchant == 'cj' %>
    <a href="<%= offer.url %>?sid=<%= current_user.id %>" target="_blank">
  <% else %>
    <a href="<%= offer.url %>" target="_blank">
  <% end %>

  <% if offer.merchant == 'aw' %>
    <a href="<%= offer.url %>&clickref=<%= current_user.id %>" target="_blank">
  <% else %>
    <a href="<%= offer.url %>" target="_blank">
  <% end %>

Is there any way to consolidate them to cleaner code as well as making them work smoothly?

1
  • 2
    You should put your conditional logic into your controller, assign the result to a variable, and then refer to that variable in your view. Don't fill a view with tests, do it all beforehand. Ruby and ERB are not PHP. Commented Nov 21, 2015 at 4:10

2 Answers 2

3

The code can be simplified into a single helper function like so in your helper file:

def merchant_link(merchant, url, user_id)
  case merchant
  when "webgains", "aw"
    "<a href=\"#{url}&clickref=#{user_id}\" target=\"_blank\">".html_safe
  when "cj"
    "<a href=\"#{url}?sid=#{user_id}\" target=\"_blank\">".html_safe
  when "rakuten"
    "<h1>WOOP</h1>".html_safe
  else
    "<h1>FAIL</h1>".html_safe
  end
end

And then call the helper function in your view:

<%= merchant_link(offer.merchant, offer.url, current_user.id) %>

You'll need to refactor your logic because there are ambiguities in your if else statement.

This might not be the best solution(I would use link_to to do the complete <a> block instead of only returning the open tag).

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

Comments

0

You need to use if..elsif..else..end or case..when..end since your conditions are on the same variable:

<% if offer.merchant == 'webgains' or offer.merchant == 'aw' %>
  <a href="<%= offer.url %>&clickref=<%= current_user.id %>" target="_blank">

<% elsif offer.merchant == 'rakuten' %>
  <h1>WOOP</h1>

<% elsif offer.merchant == 'cj' %>
  <a href="<%= offer.url %>?sid=<%= current_user.id %>" target="_blank">

<% else %>
  <h1>FAIL</h1>
  <a href="<%= offer.url %>" target="_blank">
<% end %>

Read "Ruby if...else, case, unless" for more about conditional statements.

Comments

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.