Class: ActiveRecord::MessagePack::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/message_pack.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Encoder

Returns a new instance of Encoder.



61
62
63
64
# File 'lib/active_record/message_pack.rb', line 61

def initialize
  @entries = []
  @refs = {}.compare_by_identity
end

Instance Attribute Details

#entries ⇒ Object (readonly)

Returns the value of attribute entries.



59
60
61
# File 'lib/active_record/message_pack.rb', line 59

def entries
  @entries
end

Instance Method Details

#add_cached_associations(record, entry) ⇒ Object



94
95
96
97
98
99
100
# File 'lib/active_record/message_pack.rb', line 94

def add_cached_associations(record, entry)
  record.class.normalized_reflections.each_value do |reflection|
    if record.association_cached?(reflection.name) && record.association(reflection.name).loaded?
      entry << reflection.name << encode(record.association(reflection.name).target)
    end
  end
end

#build_entry(record) ⇒ Object



86
87
88
89
90
91
92
# File 'lib/active_record/message_pack.rb', line 86

def build_entry(record)
  [
    ActiveSupport::MessagePack::Extensions.dump_class(record.class),
    record.attributes_for_database,
    record.new_record?
  ]
end

#encode(input) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/active_record/message_pack.rb', line 66

def encode(input)
  if input.is_a?(Array)
    input.map { |record| encode_record(record) }
  elsif input
    encode_record(input)
  end
end

#encode_record(record) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
# File 'lib/active_record/message_pack.rb', line 74

def encode_record(record)
  ref = @refs[record]

  if !ref
    ref = @refs[record] = @entries.size
    @entries << build_entry(record)
    add_cached_associations(record, @entries.last)
  end

  ref
end