Consts for symbols or too anal?

Soliciting some opinions here.

I keep having this urge to create constants for some of my symbol
keys, so the Ruby interpreter catches my typos. I’m wondering how
other developers handle this / what Rails best practices are.

The urge is strong for keys that are shared between lots of
controllers and views. E.g., instead of flash[:warning], I want to use
flash[WARNING] and make a WARNING=:warning const that’s included in
ApplicationController and ApplicationHelper. I have some “global”
param names I also want to do this for, like the sort column and
“redirect back” URL (which are handled by ApplicationController
methods and used in lots of templates).

I hesitate to do this because I’ve never read a code example that does
it. And of course I could take it to a ridiculous extreme by consting
every param name in every form, so there has to be balance and
discretion.

So should I do this? Or is the Rails way to stick with :warning and
use tests to catch my typos? Exhaustive testing seems kinda infeasible
for this. Like, I have a lot of error paths with a lot of different
flash error messages, and I have a lot of candidate columns to sort
by. But maybe I’m just lazy.

Thanks,
Jeff

Jeff B. wrote:

Soliciting some opinions here.

I keep having this urge to create constants for some of my symbol
keys, so the Ruby interpreter catches my typos. I’m wondering how
other developers handle this / what Rails best practices are.

The urge is strong for keys that are shared between lots of
controllers and views. E.g., instead of flash[:warning], I want to use
flash[WARNING] and make a WARNING=:warning const that’s included in
ApplicationController and ApplicationHelper. I have some “global”
param names I also want to do this for, like the sort column and
“redirect back” URL (which are handled by ApplicationController
methods and used in lots of templates).

I hesitate to do this because I’ve never read a code example that does
it. And of course I could take it to a ridiculous extreme by consting
every param name in every form, so there has to be balance and
discretion.

So should I do this? Or is the Rails way to stick with :warning and
use tests to catch my typos? Exhaustive testing seems kinda infeasible
for this. Like, I have a lot of error paths with a lot of different
flash error messages, and I have a lot of candidate columns to sort
by. But maybe I’m just lazy.

Thanks,
Jeff

Hi Jeff,

I would prefer to write methods to encapsulate the behavior, and if you
mistype a method name you’ll get a NoMethodError. You can put this in
application.rb:

def flash_warning(msg)
flash[:warning] = msg
end

Then just call:

flash_warning ‘hello’

With a little metaprogramming you could DRYly generate methods for other
flash levels that you want to use:

%w(info warning error).each do |level|
define_method “flash_#{level}” do |msg|
flash[level.to_sym] = msg
end
end