Sha256: 453250fd6d3d22d156f4fa298af9dfaa287d715e6cdd5515c128f8b30234a7e3

Contents?: true

Size: 1.94 KB

Versions: 3

Compression:

Stored size: 1.94 KB

Contents

module Lotus
  module Model
    # Abstract coercer
    #
    # It can be used as super class for custom mapping coercers.
    #
    # @since 0.5.0
    #
    # @see Lotus::Model::Mapper
    #
    # @example Postgres Array
    #   require 'lotus/model/coercer'
    #   require 'sequel/extensions/pg_array'
    #
    #   class PGArray < Lotus::Model::Coercer
    #     def self.dump(value)
    #       ::Sequel.pg_array(value) rescue nil
    #     end
    #
    #     def self.load(value)
    #       ::Kernel.Array(value) unless value.nil?
    #     end
    #   end
    #
    #   Lotus::Model.configure do
    #     mapping do
    #       collection :articles do
    #         entity     Article
    #         repository ArticleRepository
    #
    #         attribute :id,    Integer
    #         attribute :title, String
    #         attribute :tags,  PGArray
    #       end
    #     end
    #   end.load!
    #
    #   # When the entity is serialized, it calls `PGArray.dump` to store `tags`
    #   # as a Postgres Array.
    #   #
    #   # When the record is loaded (unserialized) from the database, it calls
    #   # `PGArray.load` and returns a Ruby Array.
    class Coercer
      # Deserialize (load) a value coming from the database into a Ruby object.
      #
      # When inheriting from this class, it's a good practice to return <tt>nil</tt>
      # if the given value it's <tt>nil</tt>.
      #
      # @abstract
      #
      # @raise [TypeError] if the value can't be coerced
      #
      # @since 0.5.0
      #
      # @see Lotus::Model::Mapping::Coercers
      def self.load(value)
        raise NotImplementedError
      end

      # Serialize (dump) a Ruby object into a value that can be store by the database.
      #
      # @abstract
      #
      # @raise [TypeError] if the value can't be coerced
      #
      # @since 0.5.0
      #
      # @see Lotus::Model::Mapping::Coercers
      def self.dump(value)
        self.load(value)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lotus-model-0.5.2 lib/lotus/model/coercer.rb
lotus-model-0.5.1 lib/lotus/model/coercer.rb
lotus-model-0.5.0 lib/lotus/model/coercer.rb