Martlark
Martlark

Reputation: 14581

How to get values from Ruby class depending on another value

I have a bit of code that formats an editing page depending on how many values a question has.

  <% ([email protected]_count.to_i).each do |qvalue| %>
    <% case qvalue
         when 1
          answer_value = @answer.value1
        when 2
          answer_value = @answer.value2
        when 3
          answer_value = @answer.value3
        when 4
          answer_value = @answer.value4
        when 5
          answer_value = @answer.value5
        end %>
       <label for="answer[value<%=qvalue%>]" class="fieldLabel" >Value<%=qvalue%></label>
      <input type="text" id="answer[value<%=qvalue%>]" name="answer[value<%=qvalue%>]" 
        value="<%=answer_value%>" 
      />
   <% end %>

That looks very messy and not extensible. How can I replace the case statement with something that does not require me have a case for each value1..n class variable?

Upvotes: 0

Views: 124

Answers (3)

Martlark
Martlark

Reputation: 14581

I have success with the old stand by, dynamic code, ie: the eval.

<% answer_value = eval( '@answer.value' + qvalue.to_s ) %>

or more correctly, as pointed out by Abe

<% answer_value = @answer.send( 'value'+qvalue.to_s) %>

for some reason unknown, this would not work.

<% answer_value = @answer.send( 'value#{qvalue}' ) %>

Upvotes: 0

Abe Voelker
Abe Voelker

Reputation: 31604

If you're using a decent ORM (e.g. DataMapper) you should be able to specify what the database fields map to. Otherwise a simple fix for your current situation could be something like this:

class Answer
  def value(i)
    self.send("value#{i}")
  end
end

Upvotes: 0

Roger
Roger

Reputation: 7612

Put the answer values in a hash, then you can get the values with one statement. You could put this in a helper methods.

values = {1 => 'my value 1', 2 => 'my value'}
answer_value = values[qvalue]

Upvotes: 1

Related Questions