Sha256: 62a78e792ec6444abb0a0044050c09355e4e4a2f34eec5871683416bb4414c39

Contents?: true

Size: 988 Bytes

Versions: 22

Compression:

Stored size: 988 Bytes

Contents

require 'active_support/time'

module ApiResource

  module Typecast

    ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/

    module TimeTypecaster

      def self.from_api(value)
        return value if value.is_a?(Time)
        value = value.to_s
        return nil if value.empty?

        if value =~ ApiResource::Typecast::ISO_DATETIME
          micro = ($7.to_f * 1_000_000).to_i
          return self.new_time($1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, micro)
        end

        time_info = Date._parse(value)
        time_info[:micro] = ((time_info[:sec_fraction].to_f % 1) * 1_000_000).to_i

        new_time(*time_info.values_at(:year, :mon, :mday, :hour, :min, :sec, :micro))

      end

      def self.to_api(value)
        return value.to_s
      end

      protected

      def self.new_time(*args)
        year = args.first
        return nil if year.nil? || year == 0
        Time.utc(*args) rescue nil
      end

    end

  end

end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
api_resource-0.6.21 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.20 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.19 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.18 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.17 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.16 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.15 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.14 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.13 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.12 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.11 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.9 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.10 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.8 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.7 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.6 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.5 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.4 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.3 lib/api_resource/typecasters/time_typecaster.rb
api_resource-0.6.2 lib/api_resource/typecasters/time_typecaster.rb