Class: OpenStruct

Inherits:
Object show all
Defined in:
lib/lite/ruby/open_struct.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) {|_self| ... } ⇒ OpenStruct

Returns a new instance of OpenStruct.

Yields:

  • (_self)

Yield Parameters:

  • _self (OpenStruct)

    the object that the method was called on



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/lite/ruby/open_struct.rb', line 8

def initialize(hash = nil, &block)
  @table = if block && block.arity == 2
             Hash.new(&block)
           else
             {}
           end

  hash&.each do |key, val|
    @table[key.to_sym] = val
    new_ostruct_member(key)
  end

  yield self if block && block.arity == 1
end

Instance Method Details

#[](key) ⇒ Object



23
24
25
26
# File 'lib/lite/ruby/open_struct.rb', line 23

def [](key)
  key = key.to_sym unless key.is_a?(Symbol)
  @table[key]
end

#[]=(key, val) ⇒ Object

Raises:

  • (TypeError)


28
29
30
31
32
33
# File 'lib/lite/ruby/open_struct.rb', line 28

def []=(key, val)
  raise TypeError, "can't modify frozen #{self.class}", caller(1) if frozen?

  key = key.to_sym unless key.is_a?(Symbol)
  @table[key] = val
end

#attributesObject



35
36
37
# File 'lib/lite/ruby/open_struct.rb', line 35

def attributes
  each_pair.with_object({}) { |(key, val), hash| hash[key] = val }
end

#replace(args) ⇒ Object



39
40
41
# File 'lib/lite/ruby/open_struct.rb', line 39

def replace(args)
  args.each_pair { |key, val| send("#{key}=", val) }
end