Sha256: ab2ed384e9e957dfad2956fbfc221ffdc046f57e6b572133b22f932d3456cd68

Contents?: true

Size: 1.17 KB

Versions: 26

Compression:

Stored size: 1.17 KB

Contents

require 'json'

module PropertySets
  module Casting
    FALSE = [ "false", "0", "", "off", "n" ]

    class << self
      def read(type, value)
        return nil if value.nil?

        case type
        when :string
          value
        when :datetime
          Time.parse(value).in_time_zone
        when :float
          value.to_f
        when :integer
          value.to_i
        when :boolean
          !false?(value)
        when :serialized
          # deserialization happens in the model
          value
        end
      end

      def write(type, value)
        return nil if value.nil?

        case type
        when :datetime
          if value.is_a?(String)
            value
          else
            value.in_time_zone("UTC").to_s
          end
        when :serialized
          # write the object directly.
          value
        when :boolean
          false?(value) ? "0" : "1"
        else
          value.to_s
        end
      end

      def deserialize(value)
        return nil if value.nil? || value == "null"
        JSON.parse(value)
      end

      private

      def false?(value)
        FALSE.include?(value.to_s.downcase)
      end
    end
  end
end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
property_sets-2.10.0 lib/property_sets/casting.rb
property_sets-2.9.1 lib/property_sets/casting.rb
property_sets-2.9.0 lib/property_sets/casting.rb
property_sets-2.8.0 lib/property_sets/casting.rb
property_sets-2.7.0 lib/property_sets/casting.rb
property_sets-2.6.0 lib/property_sets/casting.rb