Forum: Ruby on Rails Storage of constants

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.
9ced25040ef51a7d985591aa452d9e18?d=identicon&s=25 Ryan Glover (prion)
on 2007-01-14 02:00
Hello,

For a number of my models I have many constant key value pairs
(sometimes dozens).  I have considered putting them in the model but it
ends up creating a very cluttered model file.  Is there an approvaed
approach to having an external data file that is associated with a
model?  Should I use a yaml file of the same name? xml?  csv?
Recommendations are appreciated.

Thanks,
Ryan Glover
http://www.prioninteractive.com
D0cd6b10e01bacb976b3b815a9c660bc?d=identicon&s=25 Alex Wayne (squeegy)
on 2007-01-14 09:54
Ryan Glover wrote:
> Hello,
>
> For a number of my models I have many constant key value pairs
> (sometimes dozens).  I have considered putting them in the model but it
> ends up creating a very cluttered model file.  Is there an approvaed
> approach to having an external data file that is associated with a
> model?  Should I use a yaml file of the same name? xml?  csv?
> Recommendations are appreciated.
>
> Thanks,
> Ryan Glover
> http://www.prioninteractive.com

You could have a subfolder of app/models called constants.

#app/models/foo.rb
require 'constants/foo'
class Foo < AR::B
  include FooConstants
  self.bar = BAZ
end

#app/models/constants/foo.rb
module FooConstants
  BAZ = "Foobar!"
end
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2007-01-19 16:31
(Received via mailing list)
Hi --

On Sun, 14 Jan 2007, Ryan Glover wrote:

>
> Hello,
>
> For a number of my models I have many constant key value pairs
> (sometimes dozens).  I have considered putting them in the model but it
> ends up creating a very cluttered model file.  Is there an approvaed
> approach to having an external data file that is associated with a
> model?  Should I use a yaml file of the same name? xml?  csv?
> Recommendations are appreciated.

How about Ruby? :-)  Just define some constants and pull them in at
runtime.  You can put things in lib/ and then require them from your
model file(s), or from the bottom of environment.rb.  For example, you
could create a file called extra_data.rb:

   module ExtraData
     COLORS = %w{ red orange yellow }
   end

Then in your model file:

   require 'extra_data'
   # now you have access to ExtraData::COLORS.


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
    (See what readers are saying!  http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)
This topic is locked and can not be replied to.