Last active
December 25, 2015 02:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Parser.new(hash).parse()