Class: Replicate::Object

Inherits:
Object
  • Object
show all
Defined in:
lib/replicate/object.rb

Overview

Simple OpenStruct style object that supports the dump and load protocols. Useful in tests and also when you want to dump an object that doesn’t implement the dump and load methods.

>> object = Replicate::Object.new :name => 'Joe', :age => 24
>> object.age
>> 24
>> object.attributes
{ 'name' => 'Joe', 'age' => 24 }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id = nil, attributes = {}) ⇒ Object

Returns a new instance of Object.



16
17
18
19
20
# File 'lib/replicate/object.rb', line 16

def initialize(id=nil, attributes={})
  attributes, id = id, nil if id.is_a?(Hash)
  @id = id || self.class.generate_id
  self.attributes = attributes
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



14
15
16
# File 'lib/replicate/object.rb', line 14

def attributes
  @attributes
end

#idObject

Returns the value of attribute id.



13
14
15
# File 'lib/replicate/object.rb', line 13

def id
  @id
end

Class Method Details

.generate_idObject



52
53
54
55
# File 'lib/replicate/object.rb', line 52

def self.generate_id
  @last_id ||= 0
  @last_id += 1
end

.load_replicant(type, id, attrs) ⇒ Object



47
48
49
50
# File 'lib/replicate/object.rb', line 47

def self.load_replicant(type, id, attrs)
  object = new(generate_id, attrs)
  [object.id, object]
end

Instance Method Details

#[](key) ⇒ Object



27
28
29
# File 'lib/replicate/object.rb', line 27

def [](key)
  @attributes[key.to_s]
end

#[]=(key, value) ⇒ Object



31
32
33
# File 'lib/replicate/object.rb', line 31

def []=(key, value)
  @attributes[key.to_s] = value
end

#dump_replicant(dumper, opts = {}) ⇒ Object



43
44
45
# File 'lib/replicate/object.rb', line 43

def dump_replicant(dumper, opts={})
  dumper.write self.class, @id, @attributes, self
end

#write_attribute(key, value) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/replicate/object.rb', line 35

def write_attribute(key, value)
  meta = (class<<self;self;end)
  meta.send(:define_method, key) { value }
  meta.send(:define_method, "#{key}=") { |val| write_attribute(key, val) }
  @attributes[key.to_s] = value
  value
end