Forum: Ruby on Rails storing a static array

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Richard S. (Guest)
on 2009-01-04 22:50
In the spirit of keeping my app DRY, i would like to store an array of
strings, and call this array in a few views and possibly in my
controller.

Where is the best place to declare an application wide static variable?
And is this possible?

array = ['why should', 'I have to copy this', 'every time i want to use
it']
(Guest)
on 2009-01-04 22:58
(Received via mailing list)
Well, if it's not going to change, you make it a constant.
Constants in ruby are in uppercase.
MY_ARRAY =  ['why should', 'I have to copy this', 'every time i want
to use > it']
Normally this should be enough, but if you want to go extra safe you
can freeze it, since an array is an object (http://www.ruby-doc.org/
core/classes/Object.html#M000354).

where to put it in Rails: one option is to declare it in a file in the
lib directory.  Rails loads what is in lib.
To make sure it will never conflict with any other, you could put it
into a module, and call it as
ModuleName::MY_ARRAY

Elise
Stephen B. (Guest)
on 2009-01-04 23:02
(Received via mailing list)
You can also look at using an external configuration file instead of
constants:
http://www.stephenbartholomew.co.uk/2008/8/22/simp....
Check out the comments for further ideas.

Steve
(Guest)
on 2009-01-04 23:10
(Received via mailing list)
you're right, that is cleaner.
(Guest)
on 2009-01-04 23:13
(Received via mailing list)
unless you really want an array, for some reason
Richard S. (Guest)
on 2009-01-04 23:21
Thanks a bunch for the help, for now its just one array, but sooner or
later i'm sure I'll want to branch out to your yml solution. Appreciate
the help!!!
This topic is locked and can not be replied to.