1

In ruby what's a nice way of choosing which array to traverse conditionally?

If condition is true -> use array 1 if not use array B.

I tried the following but it didn't work.

   <% if  @post.active ?  %>
        <% Post::A_OPTIONS.each do |option|  %>
    <%else %>
        <% Post::B_OPTIONS.each do |option| %>
    <%end%>
      <br><%= radio_button_tag 'option', option, @option == option %>
      <%= option.humanize %>
    <% end %>

3 Answers 3

4

You should put your business logic into your model. such as

class Post
  def options
    active ? Post::A_OPTIONS : Post::B_OPTIONS
  end
end

then in your view,

<% @post.options.each do |option| %>
  <%= radio_button_tag 'option', option, @option == option %>
  <%= option.humanize %>
<% end %>

In this case, your view is isolated from how the options are generated, and both options logic and view logic are simple and clean

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

2 Comments

As you are in the Post class, you can simplify with: self.active ? A_OPTIONS : B_OPTIONS
You shouldn't need the self either.
1

What about this?

<% (@post.active ? Post::A_OPTIONS : Post::B_OPTIONS).each do |option|  %>
  <br><%= radio_button_tag 'option', option, @option == option %>
  <%= option.humanize %>
<% end %>

Comments

0

How about you define a method on the Post model that simply returns the correct options? e.g.

class Post < ActiveRecord::Base
  A_OPTIONS = [...];
  B_OPTIONS = [...];

  # other stuff

  def options
    if active
      A_OPTIONS
    else
      B_OPTIONS
    end
  end
end

And then your view will be dead simple:

<% @post.options.each do |option|  %>
  <br><%= radio_button_tag 'option', option, @option == option %>
  <%= option.humanize %>
<% end %>

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.