Sha256: 3585372c266226c2a82c646f6942c43d2f84f82b0c45f3a91be0daf324036d2d

Contents?: true

Size: 824 Bytes

Versions: 1

Compression:

Stored size: 824 Bytes

Contents

require_relative "base"

class StoreSchema::Converter::DateTime
  include StoreSchema::Converter::Base

  # @return [String] the database format for storing a DateTime object.
  #
  DATETIME_DB_FORMAT = "%Y-%m-%d %H:%M:%S.%N"

  # Converts the {#value} to a database-storable value.
  #
  # @return [String, false] false if {#value} is an invalid date-type.
  #
  def to_db
    begin
      case value
      when ::DateTime, ::Date
        value.strftime(DATETIME_DB_FORMAT)
      when ::Time
        value.utc.strftime(DATETIME_DB_FORMAT)
      when ::String
        ::DateTime.parse(value).strftime(DATETIME_DB_FORMAT)
      else
        false
      end
    rescue
      false
    end
  end

  # Converts the {#value} to a Ruby-type value.
  #
  # @return [DateTime]
  #
  def from_db
    ::DateTime.parse(value)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
store_schema-0.0.1 lib/store_schema/converter/date_time.rb