yaru yaru - 2 months ago 7
Ruby Question

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

I want to use

save_form_data
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'])
end

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


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
params
is of type
Hash
and if it is - just ignore
foobar
. But it solves only half of a problem because new calls of type:
save_form_data(params)
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'])
else
process(params, foobar)
end
end

Answer

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.

Comments