Class: BetterStruct

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/better_struct.rb,
lib/better_struct/version.rb

Constant Summary collapse

VERSION =
"0.1.3"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ BetterStruct

Returns a new instance of BetterStruct.



10
11
12
13
14
15
16
17
# File 'lib/better_struct.rb', line 10

def initialize(value)
  @value = value
  @defined_methods = {}

  if value && value.respond_to?(:each_pair)
    value.each_pair { |key, value| @defined_methods[underscore(key.to_s)] = value }
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object (private)



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

def method_missing(*args, &block)
  method_name = args.first.to_s

  if value.respond_to?(method_name)
    result = wrap(value.public_send(*args, &wrap_block_arguments(*args, &block)))

    method_name == "map" ? unwrap_items(result) : result
  else
    wrap(@defined_methods[method_name])
  end
end

Instance Attribute Details

#value ⇒ Object (readonly)

Returns the value of attribute value.



7
8
9
# File 'lib/better_struct.rb', line 7

def value
  @value
end

Instance Method Details

#==(other) ⇒ Object



19
20
21
# File 'lib/better_struct.rb', line 19

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

#inspect ⇒ Object



23
24
25
# File 'lib/better_struct.rb', line 23

def inspect
  "#{ self.class }<#{ @value.inspect }>"
end