开发者

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开发者_Go百科 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


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.


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


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜