Sha256: aede3dcc6798bf47397a04b595dad999f4da67756676dfd6575d018db4b3e53a

Contents?: true

Size: 1.18 KB

Versions: 5

Compression:

Stored size: 1.18 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.new("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

5 entries across 5 versions & 1 rubygems

Version Path
ensurance-0.1.11 lib/ensurance/time_ensure.rb
ensurance-0.1.10 lib/ensurance/time_ensure.rb
ensurance-0.1.9 lib/ensurance/time_ensure.rb
ensurance-0.1.8 lib/ensurance/time_ensure.rb
ensurance-0.1.7 lib/ensurance/time_ensure.rb