Class: OpenStruct

Inherits:
Object show all
Defined in:
opal/stdlib/ostruct.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) ⇒ OpenStruct

Returns a new instance of OpenStruct



2
3
4
5
6
7
8
# File 'opal/stdlib/ostruct.rb', line 2

def initialize(hash = nil)
  @table = {}

  hash.each_pair {|key, value|
    @table[key.to_sym] = value
  } if hash
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



18
19
20
21
22
23
24
# File 'opal/stdlib/ostruct.rb', line 18

def method_missing(name, *args)
  if name.end_with? '='
    @table[name[0 .. -2].to_sym] = args[0]
  else
    @table[name.to_sym]
  end
end

Instance Method Details

#==(other) ⇒ Object



34
35
36
37
38
# File 'opal/stdlib/ostruct.rb', line 34

def ==(other)
  return false unless other.is_a?(OpenStruct)

  @table == other.instance_variable_get(:@table)
end

#===(other) ⇒ Object



40
41
42
43
44
# File 'opal/stdlib/ostruct.rb', line 40

def ===(other)
  return false unless other.is_a?(OpenStruct)

  @table === other.instance_variable_get(:@table)
end

#[](name) ⇒ Object



10
11
12
# File 'opal/stdlib/ostruct.rb', line 10

def [](name)
  @table[name.to_sym]
end

#[]=(name, value) ⇒ Object



14
15
16
# File 'opal/stdlib/ostruct.rb', line 14

def []=(name, value)
  @table[name.to_sym] = value
end

#each_pairObject



26
27
28
29
30
31
32
# File 'opal/stdlib/ostruct.rb', line 26

def each_pair
  return enum_for :each_pair unless block_given?

  @table.each_pair {|pair|
    yield pair
  }
end

#eql?(other) ⇒ Boolean

Returns:



46
47
48
49
50
# File 'opal/stdlib/ostruct.rb', line 46

def eql?(other)
  return false unless other.is_a?(OpenStruct)

  @table.eql? other.instance_variable_get(:@table)
end

#hashObject



60
61
62
# File 'opal/stdlib/ostruct.rb', line 60

def hash
  @table.hash
end

#inspectObject



64
65
66
67
68
# File 'opal/stdlib/ostruct.rb', line 64

def inspect
  "#<#{self.class}: #{each_pair.map {|name, value|
    "#{name}=#{self[name].inspect}"
  }.join(" ")}>"
end

#to_hObject



52
53
54
# File 'opal/stdlib/ostruct.rb', line 52

def to_h
  @table.dup
end

#to_nObject



56
57
58
# File 'opal/stdlib/ostruct.rb', line 56

def to_n
  @table.to_n
end