Class: FreeStruct

Inherits:
Object show all
Defined in:
lib/common/free_struct.rb

Overview

Convert hash to object with methods

o = FreeStruct.new name: 'a'
o.name   -> 'a'
o[:name] -> 'a'
o.name = 'b'
o.name 'b'
o.name -> 'b'
o.name = nil
o.name -> nil
o.title -> raises error

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ FreeStruct

Returns a new instance of FreeStruct.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/common/free_struct.rb', line 13

def initialize hash
  @keys = hash.keys

  hash.each do |key, value|
    ivar = "@#{key}"

    instance_variable_set ivar, value

    define_singleton_method(key) do
      instance_variable_get ivar
    end

    define_singleton_method "#{key}=" do |val|
      instance_variable_set ivar, val
    end
  end
end

Instance Method Details

#[](key) ⇒ Object



31
32
33
# File 'lib/common/free_struct.rb', line 31

def [] key
  send key
end

#to_hObject



35
36
37
38
39
40
# File 'lib/common/free_struct.rb', line 35

def to_h
  @keys.inject({}) do |out, key|
    out[key] = send(key)
    out
  end
end