Ruby pipelines is easy

Alexander Merkulov
2 min readOct 30, 2016
Pipeline https://pixabay.com/en/pressure-water-line-tube-pipeline-509871/

Usually i haves task to use pipelines in our ruby/rails applications.

We can pass this goal via 3+ ways:

  1. Create complex class/module OOP structure
  2. Use futures from the ConcurrentRuby
    Example: https://gist.github.com/merqlove/6fa074c7bfa993121d018aa414670450
  3. Do it in Functional/Elixir’s way. Here i will describe this solution.

Idea is to maintain the state in memory till all calls for chained pipeline will be completed.

Look how simple it can be in the Elixir:

1..100_000  
|> Stream.map(&(&1 * 3))
|> Stream.filter(&(Integer.is_odd(&1)))
|> Enum.sum

Not it?

In the Ruby, FP way currently is really simple, we can build our pipeline via chainable_methods gem.

This gem is about 62 SLOC!

Just add chainable_methods gem to your Gemfile or install it.

gem 'chainable_methods'
# OR RUN
# $ gem install chainable_methods

Next create some example pipeline:

require 'chainable_methods'module SimpleMath
include ChainableMethods
def add(a, b=0)
a + b
end
def subtract(a, b=0)
a - b
end
def op(a)
yield(a)
end
end

Use this pipeline in your app:

Here is few methods:

chain_from set initial state at the start

unwrap output result state

SimpleMath.
chain_from(5).
add(5).
add(5).
subtract(3).
op { |a| a * 3 }.
unwrap
#result> 36

As you can see, this way is pure simple & clean. No dependency in additional structure or complex concurrent logic.

Ruby often better than we can imagine.

--

--