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



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

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



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

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

#[]=(key, val) ⇒ Object

Raises:

  • (TypeError)


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

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



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

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

#replace(args) ⇒ Object



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

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