Ruby on Rails Thursday, May 24, 2012

Michael Baldock wrote in post #1061986:
> I'm building an app that compares statistics from sports games. Each
> statistic has an "action" that defines what happened at that point in
> time, for example "player has possession" is one such action string.
>
> I use these strings to pull out / sort the statistics into meaningful
> information, so these strings are used throughout the app.
>
> Where can I declare a string constant??!

I generally prefer keeping my constants close to context where they are
used. For example if you're using a set of constants related to Player
objects then I'd do something like:

class Player < ActiveRecord::Base
HAS_POSSESSION = 'player has possession'
LOST_POSSESSION = 'player has lost possession'

# Rest of implementation
end

However, given that Ruby provides symbols, using string constants are
generally not necessary. Just use the symbol (e.g. :has_possession).

If you want to validate a symbol exists in a list then just make an
array constant containing the list of symbols (e.g STAT_ACTIONS = [
:has_possession, :lost_possession, ... ]); Put that in whatever class
makes sense and get it from there. (e.g. Player::STAT_ACTIONS).

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment