Class: EacRubyUtils::Struct

Inherits:
Object show all
Defined in:
lib/eac_ruby_utils/struct.rb

Instance Method Summary collapse

Constructor Details

#initialize(initial_data = {}) ⇒ Struct

Returns a new instance of Struct.


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

def initialize(initial_data = {})
  self.data = initial_data.symbolize_keys
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *arguments, &block) ⇒ Object


28
29
30
# File 'lib/eac_ruby_utils/struct.rb', line 28

def method_missing(method_name, *arguments, &block)
  property_method?(method_name) ? fetch(method_name) : super
end

Instance Method Details

#[](key) ⇒ Object


13
14
15
16
# File 'lib/eac_ruby_utils/struct.rb', line 13

def [](key)
  key, bool = parse_key(key)
  bool ? self[key].present? : data[key]
end

#fetch(key) ⇒ Object


18
19
20
21
# File 'lib/eac_ruby_utils/struct.rb', line 18

def fetch(key)
  key, bool = parse_key(key)
  bool ? fetch(key).present? : data.fetch(key)
end

#merge(other) ⇒ Object


23
24
25
26
# File 'lib/eac_ruby_utils/struct.rb', line 23

def merge(other)
  other = self.class.new(other) unless other.is_a?(self.class)
  self.class.new(to_h.merge(other.to_h))
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:


32
33
34
# File 'lib/eac_ruby_utils/struct.rb', line 32

def respond_to_missing?(method_name, include_private = false)
  property_method?(method_name) || super
end

#slice_fetch(*keys) ⇒ Object


36
37
38
# File 'lib/eac_ruby_utils/struct.rb', line 36

def slice_fetch(*keys)
  self.class.new(keys.map { |key| [key, fetch(key)] }.to_h)
end

#to_hObject


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

def to_h
  data.dup
end