Sha256: fd7b496d3aad4a5d41e5b9ccfa5b0b69611da9e2600a8848ed29a4944cb83feb

Contents?: true

Size: 1.33 KB

Versions: 9

Compression:

Stored size: 1.33 KB

Contents

module Spontaneous::DataMapper
  module ContentModel
    module Serialization
      def self.included(model)
        # Don't want to pollute this shared module with the accessors
        # (in case we are using this in multiple models)
        m = Module.new
        model.serialized_columns.each do |column|
          m.module_eval (<<-RB), __FILE__, __LINE__
            def #{column}
              _deserialize_column(:#{column}) { super }
            end
            def #{column}=(value)
              super(_serialize_column(:#{column}, value))
            end
          RB
        end
        model.send :include, m
      end

      def refresh
        _deserialized_values.clear
        super
      end

      private

      def _deserialized_values
        @_deserialized_values ||= {}
      end

      def _deserialize_column(column)
        cache = _deserialized_values
        unless cache.key?(column)
          cache[column] = _deserialize_value(yield)
        end
        cache[column]
      end

      def _deserialize_value(value)
        Yajl::Parser.new(:symbolize_keys => true).parse(value || "null")
      end

      def _serialize_column(column, value)
        _deserialized_values[column] = value
        _serialize_value(value)
      end

      def _serialize_value(value)
        Yajl::Encoder.new.encode(value)
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
spontaneous-0.2.0.beta9 lib/spontaneous/data_mapper/content_model/serialization.rb
spontaneous-0.2.0.beta8 lib/spontaneous/data_mapper/content_model/serialization.rb
spontaneous-0.2.0.beta7 lib/spontaneous/data_mapper/content_model/serialization.rb
spontaneous-0.2.0.beta6 lib/spontaneous/data_mapper/content_model/serialization.rb
spontaneous-0.2.0.beta5 lib/spontaneous/data_mapper/content_model/serialization.rb
spontaneous-0.2.0.beta4 lib/spontaneous/data_mapper/content_model/serialization.rb
spontaneous-0.2.0.beta3 lib/spontaneous/data_mapper/content_model/serialization.rb
spontaneous-0.2.0.beta2 lib/spontaneous/data_mapper/content_model/serialization.rb
spontaneous-0.2.0.beta1 lib/spontaneous/data_mapper/content_model/serialization.rb