I am writing an API wrapper and the endpoint takes dates in a very specific format.
The user of the API can pass in the parameters in whatever format they prefer, but regardless of what they pass in, I want to be able to clean up their input prior to submitting their query.
My question centers around the best way to update the options hash in place, and I have thought of a few possible ways to implement.
- A helper method inside the class so you can overwrite
options = reformat_hash(options)
A singleton on that specific variable
def options.clean_up! # see internals below end
Or open up
Hash
and do the cleaning from the classclass Hash def clean_hash! self.each { |key, value| if value.is_a? Date self[key] = value.strftime('%Y-%m-%d %H:%M:%S') else self[key] = value.to_s end } end end
so that I can just call it on whatever the variable may be named like:
def api_request(options={}) options.clean_hash! # the options variable is now clean and I can pass it to the api HHTParty.get(path, :query => options).parsed_response end
Is there a best practice for modifying or formatting hashes after they're passed into a method?
I feel like #3 is the neatest, but should I be worried about opening up Hash
to do this?