Transproc
Functional transformations for Ruby. It's currently used as one of the data mapping backends in Ruby Object Mapper.
Installation
Add this line to your application's Gemfile:
gem 'transproc'
And then execute:
$ bundle
Or install it yourself as:
$ gem install transproc
Usage
require 'json'
require 'transproc/all'
require 'inflecto'
# create your own local registry for transformation functions
module Functions
extend Transproc::Registry
end
# import necessary functions from external modules
module Functions
# ...
# all transformations available in the imported module
import Transproc::HashTransforations
import Transproc::ArrayTransformations
# only specific transformation (renamed into the desired local name)
import :camelize, from: Inflecto, as: :camel_case
end
# use imported transformation
transformation = Functions[:camel_case]
transformation.call 'i_am_a_camel'
# => "IAmACamel"
transformation = Functions[:map_array, Functions[:symbolize_keys] >> Functions[:rename_keys, user_name: :user]]
transformation >>= Functions[:wrap, :address, [:city, :street, :zipcode]]
transformation.call(
[
{ 'user_name' => 'Jane',
'city' => 'NYC',
'street' => 'Street 1',
'zipcode' => '123' }
]
)
# => [{:user=>"Jane", :address=>{:city=>"NYC", :street=>"Street 1", :zipcode=>"123"}}]
# define your own composable transformation easily
transformation = Functions[-> v { JSON.dump(v) }]
transformation.call(name: 'Jane')
# => "{\"name\":\"Jane\"}"
# ...or add it to registered functions via singleton method of the registry
module Functions
# ...
def self.load_json(v)
JSON.load(v)
end
end
transformation = Functions[:load_json] >> Functions[:map_array, Functions[:symbolize_keys]]
transformation.call('[{"name":"Jane"}]')
# => [{ :name => "Jane" }]
Credits
This project is inspired by the work of following people:
- Markus Schirp and morpher project
- Josep M. Bach and kleisli project
Contributing
- Fork it ( https://github.com/solnic/transproc/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request