Module: Zuck::HashDelegator

Included in:
FbObject::RawFbObject
Defined in:
lib/zuck/fb_object/hash_delegator.rb

Overview

Including this module does three things:

  1. Lets you use x[:foo] to access keys of the underlying Hash
  2. Lets you use x[:foo] = :bar to set values in the underlying Hash
  3. Lets you define which keys are to be expected in the underlying hash. These keys will become methods

Here's an example:

class MyObjectWithHash

  include Zuck::HashDelegator

  known_keys :foo, :bar

  def initialize(initial_data)
    set_data(initial_data)
  end
end

> x = MyObjectWithHash.new(foo: :foo)
> x.foo
=> :foo
> x.bar
=> nil
> x['bar'] = :everything_is_a_symbol
> x[:bar]
=> :everything_is_a_symbol
> x['bar']
=> :everything_is_a_symbol
> x.foo
=> :everything_is_a_symbol
> x.foo = :you_also_have_setters
=> :you_also_have_setters

As you can see, all string keys become symbols and the foo and bar methods were added because they are known keys

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



45
46
47
# File 'lib/zuck/fb_object/hash_delegator.rb', line 45

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#[](key) ⇒ Object



86
87
88
89
# File 'lib/zuck/fb_object/hash_delegator.rb', line 86

def [](key)
  init_hash
  @hash_delegator_hash[key.to_sym]
end

#[]=(key, value) ⇒ Object



91
92
93
94
# File 'lib/zuck/fb_object/hash_delegator.rb', line 91

def []=(key, value)
  init_hash
  @hash_delegator_hash[key.to_sym] = value
end

#dataObject



82
83
84
# File 'lib/zuck/fb_object/hash_delegator.rb', line 82

def data
  @hash_delegator_hash
end

#data=(d) ⇒ Object



78
79
80
# File 'lib/zuck/fb_object/hash_delegator.rb', line 78

def data=(d)
  set_data(d)
end

#set_data(d) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'lib/zuck/fb_object/hash_delegator.rb', line 68

def set_data(d)
  e = "You can only assign a Hash to #{self.class}, not a #{d.class}"
  raise e unless d.is_a? Hash
  hash = Hash.new
  d.each do |key, value|
    hash[(key.to_sym rescue key) || key] = value
  end
  @hash_delegator_hash = hash
end

#to_sObject



96
97
98
99
100
101
102
# File 'lib/zuck/fb_object/hash_delegator.rb', line 96

def to_s
  init_hash
  vars = @hash_delegator_hash.map do |k, v|
    "#{k}: #{v.to_json}"
  end.join(", ")
  "#<#{self.class} #{vars}>"
end