开发者

Rails - Passing an option to a method

开发者 https://www.devze.com 2023-02-12 05:01 出处:网络
I have a help method that looks a something like this: def html_format(text, width=15, string=\"<wbr />\", email_开发者_如何学JAVAstyling=false)

I have a help method that looks a something like this:

  def html_format(text, width=15, string="<wbr />", email_开发者_如何学JAVAstyling=false)

    if email_styling
       ...... stuff
    else
       ...... stuff
    end
       ...... stuff
  end

I'm having problems sending email_styling as true. Here is what I'm doing in the view:

<%= html_format(@comment.content, :email_styling => true) %>

Am I passing true incorrectly? Thanks


You are not passing it correctly. You need to do the following:

<%= html_format(@comment.content, 15, '<wbr />', true) %>

Alternatively you can use an options 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 that you can make your call like this:

<%= html_format(@comment.content, :email_styling => true) %>


Ruby doesn't have named arguments, so your method call:

html_format(@comment.content, :email_styling => true)

Is actually calling (psuedo-code):

html_format(text = @comment, width = true)

You need to specify all your function parameters in order, even if it means redundantly 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

USAGE

html_format("MY TEXT", {:email_styling => true, :width => 20})
0

精彩评论

暂无评论...
验证码 换一张
取 消