Class: MassiveRecord::ORM::Coders::Chained
- Inherits:
-
Object
- Object
- MassiveRecord::ORM::Coders::Chained
- 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
-
#dumpers ⇒ Object
readonly
Returns the value of attribute dumpers.
-
#loaders ⇒ Object
readonly
Returns the value of attribute loaders.
Instance Method Summary collapse
- #dump(object) ⇒ Object
-
#initialize(*args) ⇒ Chained
constructor
A new instance of Chained.
- #load(data) ⇒ Object
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. @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
#dumpers ⇒ Object (readonly)
Returns the value of attribute dumpers.
29 30 31 |
# File 'lib/massive_record/orm/coders/chained.rb', line 29 def dumpers @dumpers end |
#loaders ⇒ Object (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 |