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

#attributesObject



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

def attributes
  @table
end

#replace(args) ⇒ Object



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

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

#to_hash(table: true) ⇒ Object Also known as: to_h



31
32
33
34
35
# File 'lib/lite/ruby/open_struct.rb', line 31

def to_hash(table: true)
  return attributes unless table

  { table: attributes }
end

#to_json(table: true) ⇒ Object Also known as: as_json



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

def to_json(table: true)
  to_hash(table: table).to_json
end