Skip to content

Instantly share code, notes, and snippets.

@chrislwade
Created April 26, 2012 19:52
Show Gist options
  • Save chrislwade/2502532 to your computer and use it in GitHub Desktop.
Save chrislwade/2502532 to your computer and use it in GitHub Desktop.
Monkey patch Psych string to date parsing for non-date strings
require 'psych'
# NOTE(chrislwade): See https://github.com/tenderlove/psych/issues/42 for more details.
# Monkey patch to deal with strings that look like dates but aren't really
# dates. The example encountered within our context is product codes in the
# form of ####-##-## which looks like a date on the surface but is really a
# good old string. This patch simply aims to replace the buggy version of
# "date" handling with one that behaves like the new implementation in Psych
# while leaving the remaining functionality of the existing Psych version
# alone.
# Only load the patch when using a buggy version of psych.
has_buggy_psych = begin
YAML.dump('5555-55-55')
$stderr.puts "Psych is working properly! (Please remove me #{__FILE__}.)"
false
rescue ArgumentError
$stderr.puts 'Psych is mis-behaving!'
true
end
if has_buggy_psych
$stderr.puts 'Teaching Psych how to behave!'
class Psych::ScalarScanner
alias :tokenize_with_date_parsing_bug :tokenize
def tokenize(string)
return nil if string.empty?
return string if @string_cache.key?(string)
case string
when /^\d{4}-\d{1,2}-\d{1,2}$/
require 'date'
begin
Date.strptime(string, '%Y-%m-%d')
rescue ArgumentError
string
end
else
tokenize_with_date_parsing_bug(string)
end
end
end
end
@chrislwade
Copy link
Author

Updated to only monkey-patch buggy versions of psych.

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