Reputation: 13481
I have a ruby form object, xForm
that inherits from Form
.
class xForm < Form
# code
end
There is a section inside the form file called # Delegations
delegate :id, :xyz,
:email, :email=,
...
to: :user
I haven't dealt with form objects or delegations before, and wasn't able to find information by searching Google.
Can anyone explain what they are used for on a high-level?
Upvotes: 1
Views: 754
Reputation: 27747
Delegate is used if you want to easily access a value on an associated object
In your example, your Form has a user. In order to access email, you could continually type: my_form.user.email
or you could use delegation (as in your example) which means you can just type my_form.email
and the form figures out where to get the email from.
It allows you to reduce typing, but also to hide away implementation-details.
http://apidock.com/rails/Module/delegate explains it pretty well if you want more
Typically this is used for Form objects so that you can build a flatter params-structure in the view that contains the form. eg if you delegate both :email
and :email=
then you can name a field :email
in the my_form
form... and then in the controller you can just use my_form = MyForm.new(params[:my_form])
instead of having to separately instantiate the associated objects and pass the attributes specific to each.
Upvotes: 3