Sha256: be3a22862d5e131c04812ec5d1a238409ea548dadb19292b99c0e35a8db6381f

Contents?: true

Size: 805 Bytes

Versions: 2

Compression:

Stored size: 805 Bytes

Contents

# frozen_string_literal: true

require_relative "base"

class StoreSchema::Converter::DateTime < 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
    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

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
store_schema-2.0.0 lib/store_schema/converter/date_time.rb
store_schema-1.1.1 lib/store_schema/converter/date_time.rb