Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a conditional statement modifier in Rails Templates

I have a rails template (.rhtml file) generating a Javascript object. It looks something like the following:

var volumes = {
  <% for volume in @volumes %>
    <%= volume.id %> : <%= volume.data %> 
    <%= ',' unless volume === @volumes.last %>
  <% end %>
};

Note the unless statement modifier to suppress printing the comma after the last element (to satisfy Internet Explorer, which incredibly doesn't support trailing commas in JSON properties declarations).

This appears to work, but as a matter of style, do people think it is reasonable to rely on <%= value unless condition %> in the template generating an appropriate render call?

like image 740
ykaganovich Avatar asked Jan 21 '26 21:01

ykaganovich


2 Answers

I don't see why not, but generally if you find yourself conditionalizing a comma on the last member, you probably want to use join instead:

<%= @volumes.map {|v| "#{v.id} : #{v.data}"}.join "," %>
like image 189
Jim Puls Avatar answered Jan 24 '26 09:01

Jim Puls


If you would like to contruct JSON (and BTW you are constructing JavaScript Object not Array) then I suggest to use to_json method:

var volumes = <%= @volumes.inject({}){|h,v| h.merge(v.id=>v.data)}.to_json %>;

or

var volumes = <%= Hash[*@volumes.map{|v| [v.id, v.data]}.flatten].to_json %>;

Even better would be to move Ruby Hash construction to model as it is too complex for view.

class Volume
  def self.to_hash(volumes)
    Hash[*volumes.map{|v| [v.id, v.data]}.flatten]
  end
end

and then in view you can put much simpler code:

var volumes = <%= Volume.to_hash(@volumes).to_json %>;
like image 32
Raimonds Simanovskis Avatar answered Jan 24 '26 11:01

Raimonds Simanovskis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!