I'm using the Google charts API to generate a pie chart in my Rails application. However, I'm having a problem passing local variables to the def in the helper. The def takes a 2D array of [label, value] pairs. It doesn't like it when I try to pass a local variable in as the value. These are calculated ahead of time and are in currency format. Putting the variable in quotes or in #{}
doesn't work either.
application_helper.rb
def pie_chart(data, options = {})
options[:width] ||= 250
options[:height] ||= 100
options[:colors] = %w(F5DD7E 0DB2AC FC8D4D FC694D FABA32 704948 968144 C08FBC ADD97E)
dt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-."
options[:divisor] ||= 1
options[:title] ||= "Energy Costs"
while (data.map { |k,v| v }.max / options[:divisor] >= 4096) do
options[:divisor] *= 20
end
opts = {
开发者_运维技巧:cht => "p",
:chd => "e:#{data.map{|k,v|v=v/options[:divisor];dt[v/64..v/64]+dt[v%64..v%64]}}",
:chl => "#{data.map { |k,v| CGI::escape(k)}.join('|')}",
:chs => "#{options[:width]}x#{options[:height]}",
:chco => options[:colors].slice(0, data.length).join(','),
:chf => "bg,s,FFFFFF00",
:chtt => "#{options[:title]}"
}
The def call in the view:
<%= pie_chart( [["Light Cost", #{light_cost}], ["Small Appliance Cost", #{sm_appl_cost}]], :width => 550, :height => 200) %>
How do I pass the local variables?
What's the error you get? You should be able to call it like:
<%=
pie_chart(
[
["Light Cost", light_cost],
["Small Appliance Cost", sm_appl_cost]
],
{ :width => 550, :height => 200 }
)
%>
I added {}
's around the hash just to make it clearer and explicit.
Using #{var}
is not the way to do it here because that's for substitution in a string, eg "Here is the value: #{var}"
.
So that code definitely wants numeric values, but #{}
is just going to start a comment unless used inside a string, and you don't want a string there.
And actually, pie_chart as written would appear to take either a 2D array as you say OR a Hash, if the only use of it is with 2-variable .map
iterators. So you should be able to use either [["str1", light_cost], ["str2", sm_appl_cost]]
or { 'str1'=>light_cost, 'str2'=>sm_appl_cost}
.
You do need to make sure that those locals are numeric, though. Try using .to_i
or .to_f
on them if they aren't.
精彩评论