Class: Lotus::Model::Coercer

Inherits:
Object
  • Object
show all
Defined in:
lib/lotus/model/coercer.rb

Overview

Abstract coercer

It can be used as super class for custom mapping coercers.

Examples:

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.

See Also:

Since:

  • 0.5.0

Class Method Summary collapse

Class Method Details

.dump(value) ⇒ Object

This method is abstract.

Serialize (dump) a Ruby object into a value that can be store by the database.

Raises:

  • (TypeError)

    if the value can’t be coerced

See Also:

Since:

  • 0.5.0



69
70
71
# File 'lib/lotus/model/coercer.rb', line 69

def self.dump(value)
  self.load(value)
end

.load(value) ⇒ Object

This method is abstract.

Deserialize (load) a value coming from the database into a Ruby object.

When inheriting from this class, it’s a good practice to return nil if the given value it’s nil.

Raises:

  • (TypeError)

    if the value can’t be coerced

See Also:

Since:

  • 0.5.0



56
57
58
# File 'lib/lotus/model/coercer.rb', line 56

def self.load(value)
  raise NotImplementedError
end