Sha256: b74326540ddd3622af3d8e393683c5c7e828ddf4827c6582a39d91238e067db9

Contents?: true

Size: 1.1 KB

Versions: 2

Compression:

Stored size: 1.1 KB

Contents

require "bigdecimal"
require "date"
require "json"
require "time"

module Ohm
  module DataTypes
    module Type
      Integer   = lambda { |x| x.to_i }
      Decimal   = lambda { |x| BigDecimal(x.to_s) }
      Float     = lambda { |x| x.to_f }
      Boolean   = lambda { |x| Ohm::DataTypes.bool(x) }
      Time      = lambda { |t| t && (t.kind_of?(::Time) ? t : ::Time.parse(t)) }
      Date      = lambda { |d| d && (d.kind_of?(::Date) ? d : ::Date.parse(d)) }
      Timestamp = lambda { |t| t && UnixTime.at(t.to_i) }
      Hash      = lambda { |h| h && SerializedHash[h.kind_of?(::Hash) ? h : JSON(h)] }
      Array     = lambda { |a| a && SerializedArray.new(a.kind_of?(::Array) ? a : JSON(a)) }
    end

    def self.bool(val)
      case val
      when "false", "0" then false
      when "true", "1"  then true
      else
        !! val
      end
    end

    class UnixTime < Time
      def to_s
        to_i.to_s
      end
    end

    class SerializedHash < Hash
      def to_s
        JSON.dump(self)
      end
    end

    class SerializedArray < Array
      def to_s
        JSON.dump(self)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ohm-contrib-1.1.0 lib/ohm/datatypes.rb
ohm-contrib-1.0.1 lib/ohm/datatypes.rb