Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle view and helper-only constants in Rails

I have a constant that is only used in views, but it's used in different ways in different places. It's an array of option names, and is used for select boxes, but I also use this in other views to see if strings are found in this array, and respond accordingly.

What's the best way to handle this to keep DRY?

I initially created a constant in a helper, but that doesn't seem to be accessible in the views.

I've since switched to creating a method in a helper, that does nothing except return the constant. However, this really seems to be against the spirit of Rails, since now essentially I'm using a lower-cased constant.

I could of course stick it in a model, but it's really got nothing to do with any of the models.

like image 890
William Jones Avatar asked Feb 15 '10 23:02

William Jones


People also ask

Can we use helper method in controller rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers. This removes some of the drawbacks of including helper modules and is much cleaner solution.

Are constants global in Ruby?

Although constants look like local variables with capital letters, they have the visibility of global variables: they can be used anywhere in a Ruby program without regard to scope.

How do you use the helper method in Ruby on Rails?

A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again. And then in the view code, you call the helper method and pass it to the user as an argument.


2 Answers

You can define constants in helpers, but you will need to refer to them by their fully qualified name in your views.

application_helper.rb

module ApplicationHelper   MyConstant = "something" end 

In any view:

<%= ApplicationHelper::MyConstant %> 
like image 70
EmFi Avatar answered Sep 29 '22 14:09

EmFi


Put it in config/initializers/constants.rb and it will be availble everywhere.

like image 42
klew Avatar answered Sep 29 '22 13:09

klew