Lets you manipulate data as it's being set on an object without a lot of setter method boilerplate
Add this line to your application's Gemfile:
gem 'transformable'
And then execute:
$ bundle
Or install it yourself as:
$ gem install transformable
Use the clean
method on your objects to create a setter method that manipulates inputs:
class User < ActiveRecord::Base
include Transformable
clean(:email) {|e| e.downcase}
end
> u = User.new(email: "[email protected]")
> u.email
=> "[email protected]"
By default, nil values won't be passed through to the block. Use the skip_nil option if you want them:
class User < ActiveRecord::Base
include Transformable
clean(:email, :skip_nil => false) {|e| e || "[email protected]"}
end
> u = User.new(email: "[email protected]")
> u.email = nil
> u.email
=> "[email protected]"
I use regexes for removing forbidden characters:
class User < ActiveRecord::Base
include Transformable
clean(:email) {|e| e.gsub(/\s/, "")} # remove spaces
end
> u = User.new(email: "f o o @ b a r . c o m")
> u.email
=> "[email protected]"
Transformable works on pure ruby objects as well as ActiveRecord objects!
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Added some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request