Codectionary / Developer documentation / Ruby

Method Wrapping with prepend

prepend inserts a module before a class in method lookup. A wrapper in the module can call super to reach the class implementation. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

class Service; prepend Wrapper; end

Examples

Method Wrapping with prepend

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

module Tagged
  def label
    "[#{super}]"
  end
end
class Report
  prepend Tagged
  def label
    "monthly"
  end
end
puts Report.new.label
  1. Expected output: [monthly]
  2. Lookup finds Tagged#label first. super invokes Report#label, whose result is wrapped in brackets.

Best practices

  • Keep wrappers focused and preserve arguments and return contracts.
  • Inspect ancestors when several prepended modules make lookup order unclear.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading