Rails - passing an option to a method
I have a help method that looks something like this:
def html_format(text, width=15, string="<wbr />", email_styling=false) if email_styling ...... stuff else ...... stuff end ...... stuff end I'm having problems sending email_styling as true. Here is what I do in the view:
<%= html_format(@comment.content, :email_styling => true) %> Am I really wrong? Thanks
You are not passing it correctly. You need to do the following:
<%= html_format(@comment.content, 15, '<wbr />', true) %> Alternatively, you can use the parameter hash to pass your parameters:
def html_format(text, options = {}) opt = {:width => 15, :string => '<wbr />', :email_styling => false}.merge(options) if opt[:email_styling] ... end end So you can make your call as follows:
<%= html_format(@comment.content, :email_styling => true) %> Ruby has no named arguments, so your method calls:
html_format(@comment.content, :email_styling => true) Actually the call (psuedo-code):
html_format(text = @comment, width = true) You need to specify all the parameters of the function in order, even if it means over-passing some default values:
html_format(@comment.content, 15, '<wbr />', true) def html_format(text, user_options={}) options = { :width => 15, :string => "<wbr />", :email_styling => false } options.merge!(user_options) if options[:email_styling] ... else ... end ... end USING
html_format("MY TEXT", {:email_styling => true, :width => 20})