yaru yaru - 1 year ago 57
Ruby Question

How to gracefully process method arguments after I changed their number and types?

I want to use

method with a new signature. But currently my server has a lot of jobs in its queue that depends on old signature - server knew that method took 2 parameters, but new signature takes only a single argument.

# new signature
# params: Hash
def save_form_data(params)
process(params['catcher_token'], params['form_data'])

# old signature
# catcher_token: String, form_data: Array
def save_form_data(catcher_token, form_data)
process(catcher_token, form_data)

I think I need to change new signature method with a version that must accept 2 parameters as it did before. Then inside it I can check if
is of type
and if it is - just ignore
. But it solves only half of a problem because new calls of type:
now will fail (I think) because method accepts 2 arguments, not 1...

# modified new signature method
def save_form_data(params, foobar)
if params.class == Hash
process(params['catcher_token'], params['form_data'])
process(params, foobar)

Answer Source

Correct. You need to make a compatible signature. And distinguish between the old and new format inside of the method. After a while, you'll be able to delete this compat layer (when all old jobs are done).

Also, don't use concrete class checks. Do "is a" checks.

if params.is_a?(Hash)

This code will work for subclasses of hash too (like HashWithIndifferentAccess, for example), whereas your code will not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download