Reformatting a method options hash 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 class

class 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 =&gt; 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?
Here, while it may look nice, the method clean_hash is not general enough to be valid across all Hashes. So adding a method such as clean_hash to all Hashes would only serve to increase the coupling which is bad. A second problem is that you are mutating your method argument which is almost never advisable.

The  solution is to define the clean method outside, perhaps as a part of your internal API object and call HHTParty.get(path, :query =&gt; clean(options)).parsed_response.

I would also define the clean method this way

def clean(opt)
  Hash[opt.collect{|k,v| [k,v.is_a? Date : v.strftime('%Y-%m-%d %H:%m:%S'):v.to_s ]}]
end