Sha256: c6f6ef2852c21b7a30a6ca23bdfe9ca893f6123d783e40e8e0dd5a8f5dd30081

Contents?: true

Size: 1.17 KB

Versions: 7

Compression:

Stored size: 1.17 KB

Contents

require 'active_support/core_ext/time'

# NOTE: https://blog.daveallie.com/clean-monkey-patching/

module Ensurance
  module TimeEnsure
    def self.prepended(base)
      base.singleton_class.prepend(ClassMethods)
    end

    module ClassMethods
      def ensure(thing)
        case thing.class.name
        when 'NilClass'
          thing
        when 'Time'
          thing
        when 'Date'
          thing.beginning_of_day
        when 'Integer', 'Float'
          ::Time.at(thing)
        when 'String'
          if thing.to_i.to_s == thing
            ::Time.at(thing.to_i)
          elsif thing.to_f.to_s == thing
            ::Time.at(thing.to_f)
          else
            ::Time.parse(thing)
          end
        else
          if thing.respond_to?(:to_time)
            thing.to_time
          else
            raise ArgumentError, "Unhandled Type for Time to ensure: #{thing.class}"
          end
        end
      end

      def ensure!(_thing)
        def ensure!(thing)
          result = self.ensure(thing)
          raise ArgumentError, "Cannot Time.ensure(#{thing})" unless result
          result
        end
      end
    end
  end
end

::Time.prepend(Ensurance::TimeEnsure)

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
ensurance-0.1.18 lib/ensurance/time_ensure.rb
ensurance-0.1.17 lib/ensurance/time_ensure.rb
ensurance-0.1.16 lib/ensurance/time_ensure.rb
ensurance-0.1.15 lib/ensurance/time_ensure.rb
ensurance-0.1.14 lib/ensurance/time_ensure.rb
ensurance-0.1.13 lib/ensurance/time_ensure.rb
ensurance-0.1.12 lib/ensurance/time_ensure.rb