New Library: Template Method (Replaces Virtual)

The Virtual library has been deprecated in favor of Template Method. Template Method provides the same functionality as Virtual and supports an edge case that Virtual doesn’t. Migration in most cases involves changing uses of the virtual macro to template_method and pure_virtual / abstract to template_method!.

Migration Examples

Activating Template Method

Before:

class SomeClass
  include Virtual
end

Virtual.activate

After:

class SomeClass
  include TemplateMethod
end

TemplateMethod.activate

Virtual Methods

Before:

virtual :some_method

virtual :some_other_method do
  ...
end

After:

template_method :some_method

template_method :some_other_method do
  ...
end

Pure Virtual (Abstract) Methods

Before:

pure_virtual :some_method

abstract :some_other_method

After:

template_method! :some_method

template_method! :some_other_method

Rationale

The terminology of Virtual (e.g. “pure virtual,” “abstract”) is only broadly familiar to Ruby programmers who have prior experience with C++ or Java, and isn’t particularly relevant to Ruby as a dynamic language.

Also, the Virtual library had a subtle issue in rare cases where the macro was invoked after the concrete implementation was defined. The virtual macro silently overrides any concrete implementation that had been declared prior to the macro invocation.

Before:

class SomeClass
  include Virtual

  def some_method
    :some_concrete_result
  end

  virtual :some_method do
    :some_default_result
  end
end

# > SomeClass.new.some_method
#=> :some_default_result

After:

class SomeClass
  include TemplateMethod

  def some_method
    :some_concrete_result
  end

  template_method :some_method do
    :some_default_result
  end
end

# > SomeClass.new.some_method
#=> :some_concrete_result