Class: MassiveRecord::ORM::Coders::Chained

Inherits:
Object
  • Object
show all
Defined in:
lib/massive_record/orm/coders/chained.rb

Overview

If you ever need support for multiple coders, this class can help you out. Lets say you have YAML serialized data in your attributes, but what to migrate over to JSON, you can:

MassiveRecord::ORM::Coders::Chained.new(
  MassiveRecord::ORM::Coders::JSON.new,
  MassiveRecord::ORM::Coders::YAML.new
)

or

MassiveRecord::ORM::Base.coder = MassiveRecord::ORM::Coders::Chained.new({
  :load_with => [MassiveRecord::ORM::Coders::JSON.new, MassiveRecord::ORM::Coders::JSON.new],
  :dump_with => MassiveRecord::ORM::Coders::JSON.new
})

With this set we’ll first try the JSON coder, and if it fails with an encoding error we’ll try the next one in the chain.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Chained

Returns a new instance of Chained.



31
32
33
34
35
36
37
38
39
# File 'lib/massive_record/orm/coders/chained.rb', line 31

def initialize(*args)
  coders = args.extract_options!

  @loaders = args.flatten
  @dumpers = args.flatten

  @loaders = [coders[:load_with]].flatten if coders[:load_with]
  @dumpers = [coders[:dump_with]].flatten if coders[:dump_with]
end

Instance Attribute Details

#dumpersObject (readonly)

Returns the value of attribute dumpers.



29
30
31
# File 'lib/massive_record/orm/coders/chained.rb', line 29

def dumpers
  @dumpers
end

#loadersObject (readonly)

Returns the value of attribute loaders.



29
30
31
# File 'lib/massive_record/orm/coders/chained.rb', line 29

def loaders
  @loaders
end

Instance Method Details

#dump(object) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/massive_record/orm/coders/chained.rb', line 42

def dump(object)
  raise "We have no coders to dump with" if dumpers.empty?

  dumpers.each do |coder|
    begin
      return coder.dump(object)
    rescue
    end
  end

  raise "Unable to encode #{object}. Tried encode it with: #{dumpers.collect(&:class).to_sentence}"
end

#load(data) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/massive_record/orm/coders/chained.rb', line 56

def load(data)
  raise "We have no coders to load with" if loaders.empty?

  loaders.each do |coder|
    begin
      return coder.load(data)
    rescue StandardError, SyntaxError
    end
  end

  raise "Unable to parse #{data}. Tried loading it with: #{loaders.collect(&:class).to_sentence}"
end