Ruby on Rails
UnderstandingComponents

Components allow you to render the response from any controller or action and mix it with the view for your own action. So your WeblogController can display the latest GalleryImage or EventCalendar without cluttering your code with un-necessary Image or Calendar stuff.[1]

Components are deprecated according to http://rubyonrails.org/deprecation

Components are similar to Partials. A partial is a fragment of HTML in some other file which you can include in your template (thus keeping DRY). A component goes one step further, however. It actually calls another controller action. When called from a view, a component behaves very much like a partial – the HTML resulting from the action is simply included into the view template at that point. But of course, the component’s controller may have done lots of stuff behind the scenes. That’s the key difference – partials don’t do anything, they are just templates.

You would call a component when you expect the other controller has to do stuff which you’d rather not repeat. You would include a partial when all you are doing is laying out some data which you already have to hand. Think DRY - if you would have to do something which is the rightful business of another controller, then call the component.

As well as calling a component from your view, you can also call the component from your controller. You would probably do this if you had a lot of processing to do: you would want to keep the business logic in your controller and out of your view.

As a rule of thumb, if you do not need to set anything up for a component – if it just does stuff and returns HTML for your template – then call it from your view. If you need to do any work or make any decisions regarding the component then put the call into your controller. You can choose to let the component’s controller render the whole page as if it had been called by the user, or you can capture the HTML yourself using render_component_as_string() and pass it to your view template as an instance variable in the normal way.

There’s a lot you can do with components, so your best bet is to read more here . When you’ve a better idea what this is all about, watch this video to see how easily you can share components in the components directory.

Resources

See Also

Troubleshooting


1 unless you want to, of course. DRY is as DRY needs to be.

category: Understanding