Have you ever felt a need to massage your data just a little bit before working with it? This is what Massager was built for.
Add this line to your application's Gemfile:
gem 'massager'
And then execute:
$ bundle
Or install it yourself as:
$ gem install massager
To start using Massager, just include it in your classes, like so:
class ExampleClass
include Massager
attribute :foo, "bar"
end
In this scenario, the "bar" key's value will become the result foo
method
testable = ExampleClass.call({"bar" => "value"})
testable.foo #=> "value"
You can have required keys defined with strict: true
class ExampleClass
include Massager
attribute :foo, "bar", strict: true
end
It will raise an error if "bar" is not passed:
testable = ExampleClass.call({"bar" => "value"})
testable.foo #=> "value"
testable = ExampleClass.call({"baz" => "value"}) #=> raises ArgumentError
You can also pass type checks using dry-types library:
class ExampleClass
include Massager
attribute :foo, "bar", type: Types::Strict::String
end
It will raise an error if the type is not correct:
testable = ExampleClass.call({"bar" => "value"})
testable.foo #=> "value"
testable = ExampleClass.call({"bar" => 123}) #=> raises Dry::Types::ConstraintError
If you want to define your own types, check the Dry Types library. Type needs to respond to call
method, so
you can define your own
You can add bit of preprocessing via block (The type check will be preformed afer the block is executed):
class ExampleClass
include Massager
attribute :foo, "bar", type: Types::Strict::String do |v|
v.upcase
end
end
And it will have following result
testable = ExampleClass.call({"bar" => "value"})
testable.foo #=> "VALUE"
class ExampleClass
include Massager
attribute :foo, "bar", "baz", type: Types::Strict::String do |bar, baz|
"#{bar} #{baz}"
end
end
Note that if you pass multiple keys, the modifier block is mandatory
testable = ExampleClass.call({"bar" => "bar", "baz" => "baz"})
testable.foo #=> "bar baz"
The gem is available as open source under the terms of the MIT License.