Let’s be disciplined and keep model constants out of our views.
If you have anything like the below in your views, remove it! You may think that it’s a harmless way to re-use a default set in your model, but that is a lie and you need to stop believing it. The above morsel of model loitering easily leads to a full fledged model invasion, which happens slowly and over time.
The view is meant to be stupid, so give it knowledge of nothing in your domain. If you need to pass in defaults then pass them in through instance variables, locals or as default settings on new ActiveRecord models. Let an object with the responsibility of knowing what should be used make that decision and let your view simply display it.
I was recently tempted to use a Avatar::NO_IMAGE_PATH default in a view – the thought lasted a few short seconds and then I banished it from my mind. The NO_IMAGE_PATH default was better handled as a default on an Avatar that didn’t have an image.
# using this in a view Avatar::DEFAULT_IMAGE # became @avatar.image_path
If you keep a list of things that are good candidates for refactoring run the below script from app/views/ in a terminal. It will find all of the model constants laying dormant.
cd app/views/ grep -HnE "[A-Z].+::[A-Z]" *
You will see output like the below:
projects/show.html.erb:22:Avatar::DEFAULT_IMAGE users/index.html.erb:4:User::SOME_SETTING events/_list.html.erb:6:Event::DEFAULT_TIMEZONE
A small victory for clean and well factored code.