Transproc is awesome!

I’m a big fan of the Elixir programming language, so when I saw at one of the Trójmiasto Ruby Users Group meetings that its pipe operator (|>) can be imitated in Ruby, I was immediately hooked. In Elixir you use it like this:

1..100_000
  |> Enum.map(&(&1 * 3))
  |> Enum.filter(odd?)
  |> Enum.sum

Which means that the result of the preceding expression/function will be passed as the first argument to the next function. This allows writing code, which looks beautiful. Sure, it’s just a syntactic sugar, but what a beautiful one.

Now in Ruby, you can achieve a very similar thing if you use the transproc gem by our own Piotr Solnica. It’s a little bit more cumbersome as this is not built in into Ruby.

Let’s say you have a Hash, which you would like to transform to deep symbolise the keys and rename one key. Here’s how you do it:

require 'transproc/all'

# create your own local registry for transformation functions
module Functions
  extend Transproc::Registry

  import Transproc::HashTransformations
end

class SomeClass
  def transform hash
    transformation.call hash
  end

  private

  def transformation
    t(:deep_symbolize_keys) >> t(:rename_keys, user_name: :name)
  end

  def t *args
    Functions[*args]
  end
end

And if you now run it you’d get this as a result:

irb(main):022:0> hash = { 'user_name' => 'Paweł', 'country' => 'PL' }
=> { "user_name" => "Paweł", "country" => "PL" }

irb(main):023:0> SomeClass.new.transform hash
=> { :country => "PL", :name=> "Paweł" }

Neat, isn’t it?

Published by

Paweł Gościcki

Ruby/Rails programmer.