Class: MightyStruct

Inherits:
Object
  • Object
show all
Defined in:
lib/mighty_struct.rb,
lib/mighty_struct/version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ MightyStruct

Returns a new instance of MightyStruct.



21
22
23
24
25
26
27
# File 'lib/mighty_struct.rb', line 21

def initialize(object)
  unless self.class.new?(object)
    raise ArgumentError.new("Cannot create a an instance of #{self.class} for the given object!")
  end

  self.class.define_property_accessors!(self, @object = object)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

last line of defense



41
42
43
44
45
46
47
# File 'lib/mighty_struct.rb', line 41

def method_missing(method_name, *arguments, &block)
  if @object.respond_to?(method_name)
    @object.send(method_name, *arguments, &block)
  else
    super
  end
end

Class Method Details

.define_property_accessors!(mighty_struct, object) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/mighty_struct.rb', line 4

def self.define_property_accessors!(mighty_struct, object)
  if object.is_a?(Hash)
    object.keys.each do |_key|
      class_eval "        def \#{_key}\n          value = @object[\#{_key.is_a?(Symbol) ? ':' << _key.to_s : '\"' << _key << '\"'}]\n          self.class.new?(value) ? self.class.new(value) : value\n        end\n      EORUBY\n    end\n  end\nend\n", __FILE__, __LINE__ + 1

.new?(object) ⇒ Boolean

Returns:

  • (Boolean)


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

def self.new?(object)
  object.is_a?(Array) || object.is_a?(Hash)
end

Instance Method Details

#[](key) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/mighty_struct.rb', line 29

def [](key)
  # ensure indifferent access
  if @object.is_a?(Hash)
    @object[key] || @object[key.to_s] || @object[key.to_sym]
  else
    @object[key]
  end
end

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

Returns:

  • (Boolean)


49
50
51
# File 'lib/mighty_struct.rb', line 49

def respond_to_missing?(method_name, include_private = false)
  @object.respond_to?(method_name) || super
end