liveBook · Manning

Additive/pass-through hybrid

As explained in The Well-Grounded Rubyist, Fourth Edition

An additive/pass-through hybrid is an override that preserves the original method behavior while adding functionality or interface options.

An additive/pass-through hybrid overrides an existing method, calls the original implementation, and adds functionality or interface options without discarding the original behavior. section 13.2.3

A pass-through override typically follows this sequence:

  • Inspect or adapt the argument when it supports an additional representation. section 13.2.3
  • Call the original method with super, preserving behavior for adapted and unchanged arguments. section 13.2.3
  • Extend the interface while retaining the original call when no new option is supplied. section 13.2.3

Formatting Time without losing default behavior

An older Active Support override kept Time#to_s unchanged with no arguments, while adding formats such as :db, :number, and :rfc822. The current implementation rejects the extra argument, showing that the extension was version-specific. section 13.2.3

  # Layers additional behavior on DateTime#<=> so that
  # Time and ActiveSupport::TimeWithZone instances
  # can be compared with a DateTime.
  def <=>(other)
    if other.respond_to? :to_datetime
      super other.to_datetime rescue nil
    else
      super
    end
  end

This override adapts comparable objects to DateTime before delegating comparison to the original <=> method. section 13.2.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines the hybrid and traces argument adaptation plus super delegation, but stops short of a general implementation recipe.
Examples
Uses DateTime#<=> adaptation and older Active Support Time#to_s formats including :db, :number, and :rfc822.
What it assumes
Assumes familiarity with Ruby methods and core classes, while explaining super delegation and argument pass-through through examples.
What you can do after
Apply via Ruby method overrides that delegate with super while adapting arguments or adding optional interface behavior.
How it connects
Connects method overriding with super, respond_to?, DateTime conversion, and Active Support core extensions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.