Skip to content

Instantly share code, notes, and snippets.

@shernade
Last active December 25, 2015 02:39
Show Gist options
  • Save shernade/6903927 to your computer and use it in GitHub Desktop.
Save shernade/6903927 to your computer and use it in GitHub Desktop.
This class parse a hash of params looking for a date field and parse its value to timestamp
class Parser
def initialize(hash)
@hash = hash
end
def parse()
@hash.inject({}) do |h, (k, v)|
h[k] = parse_element(k, v)
h
end
end
private
def parse_element(parent, element)
case element
when Array
element.map{|x| parse_element(parent, x)}
when Hash
element.inject({}) do |h, (k, v)|
h[k] = parse_element(k, v)
h
end
else
parent.match(/(_at$|^timestamp$|^datetime$|date$)/) ? parse_time(element) : element
end
end
def parse_time(element)
DateTime.strptime(element, '%m/%d/%Y').to_i if element.present?
end
end
@shernade
Copy link
Author

shernade commented Oct 9, 2013

Parser.new(hash).parse()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment