Sha256: 0f0d7009f1e35ff0525ccce6171b5d0477af1b14d72b5626c14a352cb90f9494

Contents?: true

Size: 897 Bytes

Versions: 7

Compression:

Stored size: 897 Bytes

Contents

module CouchPotato
  module Persistence
    class TypeCaster #:nodoc:
      def cast(value, type)
        if type == :boolean
          cast_boolean(value)
        else
          cast_native(value, type)
        end
      end

      private

      def cast_boolean(value)
        if [FalseClass, TrueClass].include?(value.class) || value.nil?
          value
        elsif [0, '0'].include?(value)
          false
        else
          true
        end
      end

      def cast_native(value, type)
        if type && !value.instance_of?(type)
          if type == Fixnum
            value.to_s.scan(/-?\d+/).join.to_i unless value.blank?
          elsif type == Float
            value.to_s.scan(/-?\d+\.?\d*/).join.to_f unless value.blank?
          else
            type.json_create value unless value.blank?
          end
        else
          value
        end
      end

    end
  end
end

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
couch_potato-0.5.3 lib/couch_potato/persistence/type_caster.rb
couch_potato-0.5.2 lib/couch_potato/persistence/type_caster.rb
couch_potato-0.5.1 lib/couch_potato/persistence/type_caster.rb
couch_potato-0.5.0 lib/couch_potato/persistence/type_caster.rb
davber_couch_potato-0.4.0 lib/couch_potato/persistence/type_caster.rb
couch_potato-0.4.0 lib/couch_potato/persistence/type_caster.rb
couch_potato-0.3.2 lib/couch_potato/persistence/type_caster.rb