开发者

Ruby: How do you have optional first arguments? but default trailing arguments?

开发者 https://www.devze.com 2023-03-23 07:32 出处:网络
I\'d like to have a method that is similar to this: def method_with_optional(..., user = current_user, account = cu开发者_开发百科rrent_account)

I'd like to have a method that is similar to this:

def method_with_optional(..., user = current_user, account = cu开发者_开发百科rrent_account)
...

because, I don't want to have to pass in current_user, and current_account every time. but as long as a user object isn't passed, the user formal parameter shouldn't be over-ridden.

This way I could do the following

method_with_optional(params[:id])

or

 method_with_optional(params[:id], User.new)


What you're looking for are named arguments, which is not supported in Ruby 1.8, but you may have some success with arguments.


Sorry, at the moment there is no built-in support for named parameters, you have to wait for Ruby 2.0.


An alternative to default arguments would be to assign the variable in the body of the method and to provide the User, Account arguments as a part of the params hash. You can check to see if the params contains a User and/or Account and then do the needful:

user = params[:user] || current_user
account = params[:account] || account

EDIT: If you cannot add things to the Params hash before invoking the method, then I don't know what you can do other than re-order the formal parameters in the method signature :)

0

精彩评论

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

关注公众号