Blankman
Blankman

Reputation: 267020

Will an optional parameter work in this case

I have a function like:

def set_blah
   self.prop1 = .... if new_record?
end

I want to be able to force an update even if it isn't a new record in some cases, can I just add an optional parameter here so all other calls that I have already won't break?

i.e.

def set_blah ( force )
  self.prop1 = ... if new_record? || force
end

Upvotes: 0

Views: 211

Answers (3)

Steve Ross
Steve Ross

Reputation: 4144

Yes, default parameters are simply specified in the method signature:

def set_blah(force=false)
  do_something if new_record? || force
end

You might try using options to make your calling sequence more readable:

def set_blah(options = {:force => false})
  do_something if new_record? || options[:force]
end

By specifying it this explicitly, your calling sequence is something like:

set_blah

or

set_blah(:force => true)

which seems to make it clearer at the call point what @set_blah@ does. Also, your rdoc will show the method's default arguments so it's kind of self-documenting.

Upvotes: 6

Jon Gauthier
Jon Gauthier

Reputation: 25582

Sure, just make force a default parameter, so you don't need to change your existing calls to this method:

def set_blah(force = false)
    self.prop1 = ... if new_record? or force
end

Upvotes: 0

Kyle Macey
Kyle Macey

Reputation: 8154

Yes, you can theoretically use your code AS IS. Just use set_blah(nil) for when you don't want to force.

Upvotes: 0

Related Questions