In times of form objects and Law Of Demeter enforcement, delegate_accessors
comes to rescue dry up your PORO classes.
Let's say you are a good boy and uses form objects to handle, for instance, user signs up. Most of the time you'll catch yourself delegating both readers and writers for the target model:
class SignupForm
include ActiveModel::Model
delegate :first_name, :first_name=, to: :user
delegate :project_name, to: :first_project
def submit
if valid?
# whatever your app does
end
end
def user
@user = User.new
end
def first_project
@project = Project.new
end
end
This tends to get messy when you delegate more and more attributes:
delegate :first_name, :first_name=, :last_name, :last_name=, :age, :age=, :ssn, :ssn=, :facebook_login, :facebook_login=, to: :user
You can use delegate_accessors
to slice the delegate line in half:
delegate_accessors :first_name, :last_name, :age, :ssn, :facebook_login, to: :user
If you have no ideia what form object are or why they're so important, consider digging these references:
Add this line to your application's Gemfile:
gem 'delegate_accessors'
And then execute:
$ bundle
Or install it yourself as:
$ gem install delegate_accessors
- Fork it
- 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 new Pull Request