Cent
Cent

Reputation: 881

If helper methods should not interact directly with the database in rails, Why do we put @current_user as helper method?

I read in this blog that helper methods should not interact with the database directly or manipulate data for views. These tasks should be handled by decorators.

If this is the case, why do we typically put the @current_user methods in helper modules? (In Rails)

Upvotes: 2

Views: 782

Answers (1)

EugZol
EugZol

Reputation: 6555

I will cite recap from coderwall.com

Helpers

Helpers are generic methods which can be use for different kind of objects. I create this kind of helpers link_to_update, big_image, styled_form, etc. Those methods create an html code with a css style or a standard text for example.

Partials

Partials are used to split a big view into smaller logic parts and for larger html code. I can have a partial side_menu, comment_list, header, etc.

Presenters

Presenters is for more complicated queries with two or more models. I have some partials like @page_presenter.page_in_category(ruby_category) or @user_presenter.user_following(an_article).

Decorators

Decorators should act with only one model and shouldn't take parameters (if it's possible). I can do something like this user.full_name, page.big_title or category.permalink. I use the gem Draper.

So, essentially decorators are things which take data from single model object and manipulate it in some way (for example, squishing first_name + last_name into full_name and such things).

current_user, on the other hand, definitely doesn't belong to the decorators because it doesn't deal with manipulating any object's data – it actually finds the object you need (using session/cookies data for that).

I'd say its place is in ApplicationController (or one of its specific descendants which you can build, say, AuthenticatedController or such), because you often need to know current_user in a controller itself (not its view), and it takes unneeded efforts to make your view helper method available for controller.

Upvotes: 1

Related Questions