AnApprentice
AnApprentice

Reputation: 110950

Rails - Passing an option to a method

I have a help method that looks a 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'm doing in the view:

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

Am I passing true incorrectly? Thanks

Upvotes: 6

Views: 1455

Answers (3)

Pan Thomakos
Pan Thomakos

Reputation: 34340

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) %>

Upvotes: 7

fl00r
fl00r

Reputation: 83680

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})

Upvotes: 1

Dominic
Dominic

Reputation: 3304

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)

Upvotes: 2

Related Questions