views:

209

answers:

3

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.

+1  A: 

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

klew
Seems kind of unfortunate to add a global constant when it will only ever be used in views and helpers, I'm not sure that's better than just using a method to alias it.
WIlliam Jones
+5  A: 

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 %>
EmFi
A: 

I'm trying to set up a constant structure related to menus that gets used in the helpers - but named routes don't seem to work in /config/initializers nor for a constant in ApplicationHelper. It seems like these ought to be static, and named routes makes it much more intuitive to edit, but I can't seem to find the right place to put it. It works fine as a helper method. Thoughts?