Class: MightyStruct

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

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, options = {}) ⇒ MightyStruct



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mighty_struct.rb', line 13

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

  @cache = options[:caching] == :enabled ? {} : nil

  if (@object = object).respond_to?(:keys)
    object.keys.each do |_key|
      unless respond_to?(_key)
        define_singleton_method(_key) do
          if @cache
             @cache[_key] ||= self.class.new?(value = @object[_key]) ? self.class.new(value) : value
          else
            self.class.new?(value = @object[_key]) ? self.class.new(value) : value
          end
        end
      end
    end
  end
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



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

def method_missing(method_name, *arguments, &block)
  if @object.respond_to?(method_name)
    @cache.clear if @cache # clear the properties cache, because the called method may have side-effects
    result = @object.send(method_name, *arguments, &block)

    # ensure that results of called methods are mighty structs again
    self.class.new?(result) ? self.class.new(result) : result
  else
    super
  end
end

Class Method Details

.new?(object) ⇒ Boolean



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

def self.new?(object)
  object.is_a?(Enumerable)
end

.to_object(object) ⇒ Object

in order not to pollute the instance’s method namespace this is a class method



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

def self.to_object(object)
  object.is_a?(self) ? object.instance_variable_get(:@object) : object
end

Instance Method Details

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



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

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