Class: OpenFastStruct

Inherits:
Object
  • Object
show all
Defined in:
lib/ofstruct.rb

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ OpenFastStruct

Returns a new instance of OpenFastStruct.



4
5
6
7
# File 'lib/ofstruct.rb', line 4

def initialize(args = {})
  @members = {}
  update(args)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object (private)



54
55
56
57
58
59
60
61
62
# File 'lib/ofstruct.rb', line 54

def method_missing(name, *args)
  @members.fetch(name) do
    if name[-1] == "="
      assign(name[0..-2], args.first)
    else
      delete_field(name)
    end
  end
end

Instance Method Details

#==(other) ⇒ Object



44
45
46
# File 'lib/ofstruct.rb', line 44

def ==(other)
  other.is_a?(self.class) && to_h == other.to_h
end

#delete_field(key) ⇒ Object



9
10
11
# File 'lib/ofstruct.rb', line 9

def delete_field(key)
  assign(key, self.class.new)
end

#each_pairObject



13
14
15
# File 'lib/ofstruct.rb', line 13

def each_pair
  @members.each_pair
end

#inspectObject Also known as: to_s



35
36
37
# File 'lib/ofstruct.rb', line 35

def inspect
  "#<#{self.class}#{@members.map { |key, value| " :#{key}=#{value.inspect}" }.join}>"
end

#to_aryObject



40
41
42
# File 'lib/ofstruct.rb', line 40

def to_ary
  nil
end

#to_hObject



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ofstruct.rb', line 22

def to_h
  @members.merge(@members) do |_, value|
    case value
    when Array
      value.map(&:to_h)
    when self.class
      value.to_h
    else
      value
    end
  end
end

#update(args) ⇒ Object



17
18
19
20
# File 'lib/ofstruct.rb', line 17

def update(args)
  ensure_hash!(args)
  args.each { |key, value| assign(key, value) }
end