I am working on a site that does web surveys. I have created a helper method to create a likert scale table (e.g., 5 columns + row title, strongly dislike <-> strongly like). This method accepts an array of hashes and then uses the built in Rails helper form.radio_button to unwrap the hash and build the table. The function is below:
# procedurally goes into an array of hashes and generates a likert table def likert_table(items = , f=f) result = "" # collector string items.each {|item| item.each {|attribute,text| result = result + likert_row(attribute,text,f)}} return "<table class='likert_table'> <tr class='likert_table_header_row'> <th></th> <th>Strongly Dislike</th> <th>Dislike</th> <th>Neutral</th> <th>Like</th> <th>Strongly Like</th> </tr> #{result} </table>" end
# create a row in a table with the 5 selectable radio buttons def likert_row(attribute, text, f=f) "<tr> <td align='right' class='likert_row_label'>#{f.label attribute, text}</td> <td align='center' class='likert_row'>#{f.radio_button attribute, 1}</td> <td align='center' class='likert_row'>#{f.radio_button attribute, 2}</td> <td align='center' class='likert_row'>#{f.radio_button attribute, 3}</td> <td align='center' class='likert_row'>#{f.radio_button attribute, 4}</td> <td align='center' class='likert_row'>#{f.radio_button attribute, 5}</td> </tr>" end
However, I had a few questions about refactoring.
First, do I need to pass "f" in both of those functions? I use it in the f.radio_button helper (as this method would be called inside a form_for) but it seems clunky to have to add "f" to the arguments every time.
Second, is using a string variable to collect the output of the iterations and then returning that string the best way to construct an iterative helper?
Third, is there a simpler way to iterate through this than an array of hashes? I can build a likert table like so:
<%= likert_table([:rates_fighting => "Fighting", :rates_platform => "Platform", :rates_shooter => "Shooter", :rates_action_adventure => "Action Adventure", :rates_system_sim => "System Simulator", :rates_life_sim => "Life Simulation", :rates_rpg => "Role Playing Game", :rates_mmorpg => "Online Role Playing Game", :rates_strategy => "Strategy", :rates_vehicle_sim => "Vehicle Simulation", :rates_music => "Music", :rates_puzzle => "Puzzle", :rates_sports => "Sports", :rates_casual => "Casual"], f)%>
...but it feels un-Railslike, especially with that dangling "f". Later I will be pulling these values from a database and using a collection instance variable. As a beginner ruby programmer I have hit my ceiling on this one. Any thoughts? Thanks in advance.