Class: Virtuatable::Enhancers::Base

Inherits:
Object
  • Object
show all
Extended by:
Helpers::Declarations
Defined in:
lib/virtuatable/enhancers/base.rb

Overview

Base class to be extended by all enhancers. It provides a way to declare this class as the enhancer of another class, to access the properties of the enhanced class as instance attributes.

Author:

Instance Attribute Summary collapse

Attributes included from Helpers::Declarations

#enhanced

Instance Method Summary collapse

Methods included from Helpers::Declarations

enhances

Constructor Details

#initialize(object) ⇒ Base

Returns a new instance of Base.



17
18
19
# File 'lib/virtuatable/enhancers/base.rb', line 17

def initialize(object)
  @object = object
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

That’s the heart of the enhancers mecanism. This method sends the call to the decorated object if this one can answer it, or raises an error.

Parameters:

  • name (String, Symbol)

    the name of the method to call on the decorated object.

  • args (Array)

    the arguments passed during the call to the function.

  • block (Block)

    the optional blockcode passed to the function.



26
27
28
29
30
# File 'lib/virtuatable/enhancers/base.rb', line 26

def method_missing(name, *args, &block)
  return enhance_association(name) if object.respond_to?(:associations) && object.associations.key?(name)

  object.respond_to?(name) ? object.send(name, *args, &block) : super
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



15
16
17
# File 'lib/virtuatable/enhancers/base.rb', line 15

def object
  @object
end

Instance Method Details

#enhance_association(name) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/virtuatable/enhancers/base.rb', line 39

def enhance_association(name)
  elements = object.send(name.to_sym)
  return nil if elements.nil?
  return enhance_collection(name, elements) if elements.is_a?(Enumerable)
  return elements.enhance if elements.respond_to?(:enhance)

  Virtuatable::Enhancers::Base.new(elements)
end

#enhance_collection(name, collection) ⇒ Object



48
49
50
51
52
53
# File 'lib/virtuatable/enhancers/base.rb', line 48

def enhance_collection(name, collection)
  enhancable = object.associations[name].klass.respond_to?(:enhancer)
  return collection.map(&:enhance) if enhancable

  collection.map { |item| Virtuatable::Enhancers::Base.new(item) }
end

#respond_to_missing?(name, _include_private = false) ⇒ Boolean

Determines if this object can transfer any of its calls to the decorated object.

Parameters:

  • name (String)

    the name of the called function.

Returns:

  • (Boolean)

    TRUE if the decorated object can answer the call, FALSE otherwise.



35
36
37
# File 'lib/virtuatable/enhancers/base.rb', line 35

def respond_to_missing?(name, _include_private = false)
  object.respond_to? name
end