Class: Outbox::Accessor

Inherits:
Object
  • Object
show all
Defined in:
lib/outbox/accessor.rb

Overview

Accessor is a simple object for wrapping access to either a hash’s keys or an object’s properties. You can arbitrarily get/set either. Note that with hashes, the keys are symbolized and a new hash is created - so if you set properties you’ll need to get the resulting hash from the #object method.

Example:

hash = { :a => 1, 'b' => 2 }
hash_accessor = Outbox::Accessor.new(hash)
hash_accessor[:a] #=> 1
hash_accessor[:b] #=> 2
hash_accessor[:c] #=> nil
hash_accessor[:c] = 3
hash_accessor.object[:c] #=> 3
hash_accessor.object #=> { a: 1, b: 2, c: 3 }

object = OpenStruct.new
object.a = 1
object.b = 2
object_accessor = Outbox::Accessor.new(object)
object_accessor[:a] #=> 1
object_accessor[:b] #=> 2
object_accessor[:c] #=> nil
object_accessor[:c] = 3
object_accessor.object.c #=> 3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Accessor

Returns a new instance of Accessor.



31
32
33
34
35
36
37
# File 'lib/outbox/accessor.rb', line 31

def initialize(object)
  if object.instance_of? Hash
    @object = convert_keys(object)
  else
    @object = object
  end
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



29
30
31
# File 'lib/outbox/accessor.rb', line 29

def object
  @object
end

Instance Method Details

#[](key) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/outbox/accessor.rb', line 48

def [](key)
  key = convert_key(key)
  if @object.respond_to?(key)
    @object.public_send(key)
  elsif @object.respond_to? :[]
    @object[key]
  end
end

#[]=(key, value) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/outbox/accessor.rb', line 39

def []=(key, value)
  setter = "#{key}="
  if @object.respond_to?(setter)
    @object.public_send(setter, value)
  elsif @object.respond_to? :[]=
    @object[convert_key(key)] = value
  end
end