📎 Webclip
Implementing Elixir's Pipeline in Ruby
The author describes their appreciation for Elixir’s pipeline operator |> and attempts to recreate similar behavior in Ruby as a thought experiment. Since Ruby does not allow defining a |> method and monkey‑patching Object is considered dangerous, they introduce a pipeline method that accepts Proc, Method, or UnboundMethod objects, enabling function chaining and data transformation without being tied to collections.
Reading notes#
- Elixir’s pipeline operator
|>passes the result of an expression as the first argument to the next function, enabling chained transformations. - The author has been adopting functional paradigms in Ruby to improve testability and reduce complexity, which motivated trying to implement a pipeline operator.
- An attempt to define a Ruby method named
|>fails because the Ruby interpreter treats>as a syntax error in that context. - Since
|>is unavailable, the author chooses apipelinemethod name;pipealready exists onIO, andpipelineis not an instance method in the standard library or core. - The initial implementation monkey‑patches
Object#pipeline, warning that this is a bad idea for larger or more complex apps. pipelinetakes a splat of arguments, shifts the first intofunc, and determines how to call it based on whether it is aProc,Method, orUnboundMethod.- For
ProcorMethod,pipelinecalls the function withselfas the first argument followed by any remaining arguments. - For an
UnboundMethod,pipelinebinds it toselfbefore calling it with the remaining arguments. - If the first argument to
pipelineis none of these types, it raises aNotImplementedErrorindicating the function type is not yet supported. - As a safer alternative to monkey‑patching
Object, the samepipelineimplementation can be placed in aPipeablemodule and included selectively in specific classes such asString. - Using this approach, the author demonstrates chaining a string through an
UnboundMethodforString#upcase, aProcthat formats a message, and aMethodobject created viamethod(:puts). - The example shows
pipelinesuccessively transforming'nine thousand'into an uppercased string and then interpolating it into a message printed withputs. - The author expresses a desire to use Elixir‑style syntax (
|> func1 |> func2 |> func3) but avoids modifying the Ruby interpreter itself. - They chose
Proc,Method, andUnboundMethodbecause Ruby commonly usesto_procand&methodfor passing functions around, and these objects fit that convention. UnboundMethodis included partly because the author finds it appealing and useful to bind methods to specific receivers later.- The author notes that Ruby already has many chainable methods, often through
Enumerable, which primarily targets collections such as arrays and hashes. - In contrast, the
pipelinemethod is presented as a more generic mechanism for chaining behavior without assuming iteration over a collection.
