Sha256: b804db70e3cc61da1c38cee4e84ebfb8d53893eb1735df300208e9c8c02db81f

Contents?: true

Size: 1.78 KB

Versions: 1

Compression:

Stored size: 1.78 KB

Contents

module AMF
  module Serialization
    class AMFSerializer < ActiveRecord::Serialization::Serializer      
      def initialize(record, options = {})
        super(record, options)
        @options[:amf_version] = 3
      end

      def serialize
        if @options[:amf_version] == 3
          serializer_class = AMF::AMF3Serializer
        elsif @options[:amf_version] == 0
          serializer_class = AMF::AMF0Serializer
        else
          raise AMF::AMFError, "unsupported serializer version #{@options[:amf_version]}"
        end
      
        serializer = serializer_class.new({:serializable_names => serializable_names, :options => @options})

        serializer.serialize(@record) do |s|
          add_includes do |association, records, opts|
            s.stream << add_associations(association, records, opts, s)
          end
          yield serializer if block_given?
        end
      end

      def add_associations(association, records, opts, serializer)
        result = serializer.write_utf8_vr(association.to_s)
        if records.is_a?(Enumerable)
          result << records.each { |record| record.to_amf(opts) }.join("")
        else
          if record = @record.send(association)
            result << record.to_amf(opts)
          end
        end
        result
      end
    end
  end
  
  module ActiveRecord    
    def self.included(base)
      base.send :include, InstanceMethods
    end

    module InstanceMethods
      def to_amf(options = {}, &block)
        serializer = AMF::Serialization::AMFSerializer.new(self, options)
        block_given? ? serializer.to_s(&block) : serializer.to_s
      end

      def from_amf(amf, options = {})
        options[:amf_version] ||= 3
        self.attributes = AMF.deserialize(amf, options[:amf_version])
        self
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
amfora-0.0.1 lib/amf/active_record.rb