Sha256: 6eb80d8e27cacd3ba1020c914600cb4f76af3309114b7124a2e96937d8342b6a

Contents?: true

Size: 1.36 KB

Versions: 6

Compression:

Stored size: 1.36 KB

Contents

module Id
  module Model
    module TypeCasts

      def self.cast(type, value)
        casts.fetch(type, Identity).new(value).cast
      end

      protected

      def self.register(cast)
        casts[cast.type] = cast
      end

      private

      def self.casts
        @casts ||= {}
      end

      class Cast

        def initialize(value)
          @value = value
        end

        def cast
          value.is_a?(type) ? value : conversion
        end

        def type
          self.class.type
        end

        def conversion
          raise NotImplementedError
        end

        private

        def self.type
          raise NotImplementedError
        end

        attr_reader :value

      end

      class Identity < Cast
        def cast
          value
        end
      end

      class Date < Cast

        def self.type
          ::Date
        end

        def conversion
          ::Date.parse value
        end

        TypeCasts.register(self)
      end

      class Time < Cast

        def self.type
          ::Time
        end

        def conversion
          ::Time.parse value
        end

        TypeCasts.register(self)
      end

      class Money < Cast

        def self.type
          ::Money
        end

        def conversion
          ::Money.new value.to_i
        end

        TypeCasts.register(self)
      end

    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
id-0.0.12 lib/id/model/type_casts.rb
id-0.0.11 lib/id/model/type_casts.rb
id-0.0.10 lib/id/model/type_casts.rb
id-0.0.9 lib/id/model/type_casts.rb
id-0.0.8 lib/id/model/type_casts.rb
id-0.0.7 lib/id/model/type_casts.rb