Helpers Are Best at Exposing Global UI State
Learn why helpers are the best at exposing the global UI and generating the markup.
We'll cover the following
Rails built-in helpers format data for the view or generate markup or both. If our app needs to do this, helpers are a good solution. We are also likely to need to implement view logic based on globally-stored context or state, such as the logged-in user and their authorizations. Helpers are great for this.
Global UI logic and state
As we mentioned above, almost every Rails app has a current_user
method that exposes the logged-in user. It’s common to require this on many views, either to access user-specific information or to check that the user is authorized to view different aspects of the UI. Setting a @current_user
instance variable in every controller method would be cumbersome.
Another example is feature flags. We might be rolling out a new feature to a subset of users and want to modify the UI for only those users. We may need to check if the user has been granted access to the new feature from anywhere, and an instance variable might be inconvenient or hard to maintain. Instead, we can create helpers like current_user
or feature_enabled?
that we could call from anywhere.
Helpers are also a good tool for managing markup generation. We discussed generating markup via partials, and a complex partial might become cumbersome to use. A helper can create an abstraction for calling render.
Wrapping complex partials
We created a reusable component using partials. That partial takes two parameters, one of which is optional, and the invocation of it is slightly cumbersome:
<%= render partial: "rating",
locals: { widget: @widget,
suppress_cta: true}%>
If we only need this component in a few places, maybe we can live with this invocation syntax, but if we need it in a lot of places, this is gonna get old fast. It’s also problematic because mistakes can happen, and a mistake in the locals:
hash could be hard to notice. It’s much easier to notice if we’ve called a method incorrectly. Helpers can, well, help! First, we’ll create a helper to render the partial in application_helper.rb
:
Get hands-on with 1200+ tech skills courses.