Last active
August 29, 2015 14:03
-
-
Save yaauie/b2561dfd39b2166d1918 to your computer and use it in GitHub Desktop.
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
# encoding: utf-8 | |
# | |
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
# Version 2, December 2004 | |
# | |
# Copyright (C) 2004 Ryan Biesemeyer <wtf@yaauie.com> | |
# | |
# Everyone is permitted to copy and distribute verbatim or modified | |
# copies of this license document, and changing it is allowed as long | |
# as the name is changed. | |
# | |
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
# | |
# 0. You just DO WHAT THE FUCK YOU WANT TO. | |
# | |
require 'active_support/core_ext/numeric/time.rb' | |
# DISCLAIMER: Don't use this. Just don't. | |
module String::AsDuration | |
# Takes something like "36 hours, 5 minutes" and makes an ActiveSupport::Duration | |
# @param [String] "36 hours, 5 minutes" | |
# @return [ActiveSupport::Duration] | |
def self.extract(string) | |
clean_string = string.gsub(/(,|and)/, '') | |
durations = clean_string.split(' ').each_slice(2).map do |i,p| | |
unless i =~ /\A[\d]+\z/ | |
warn("NOT A NUMBER: #{i.dump}") | |
return nil | |
end | |
unless p =~ /\A(seconds?|minutes?|hours?|days?|weeks?|fortnights?)\z/i | |
warn("NOT A TIME PERIOD: #{p.dump}") | |
return nil | |
end | |
(i.to_i).send(p.downcase) | |
end | |
durations.reduce(:+) | |
rescue => e | |
warn("CAUGHT: #{e} parsing #{string.dump}") | |
nil | |
end | |
# Don't do this. Seriously don't. | |
def self.install_globally! | |
class ::String | |
# If self is something like "36 hours, 5 minutes", returns an ActiveSupport::Duration | |
# @return [ActiveSupport::Duration] | |
def as_duration | |
String::AsDuration.extract(string) | |
end | |
end | |
warn("Some dumbass didn't heed the warnings (at #{caller.first})") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment