Refactoring Global Constants

Hi,

I’m going to ask a dumb question (sorry for that, in advance)…

What’s the most elegant syntax and form for refactoring Global Constants
out of Ruby code so they can be shared across different Ruby code files?

For example, I have a variable that shows up in three different files
and looks like:

 maxColumns = 30

I’d like to know what the most elegant way is to define it in one place
and share it, across files.

BTW, if there’s a book or document out there that specifically talks
about different ways to refactor Ruby Code, I’d appreciate a pointer to
it.

Thanks for your help,

FG

Frank G. wrote:

For example, I have a variable that shows up in three different files
and looks like:

 maxColumns = 30

I’d like to know what the most elegant way is to define it in one place
and share it, across files.

The best way to define a constant is using a constant :slight_smile:

MAX_COLUMNS = 30

Put this in a source file (e.g. limits.rb) then require ‘limits’ where
you need it.

For any code which might be re-used or shared, you’d be better keeping
your constants in their own namespace:

module MyStuff
MAX_COLUMNS = 30
end

This can be referenced as MyStuff::MAX_COLUMNS, but usually your code
would also be inside the same module, so it can just use MAX_COLUMNS.

If your code consists mainly of one class, then just put the constants
inside that class (remember that a Class is also a Module)

class Foo
MAX_COLUMNS = 30
end

require ‘foo/constants’
class Foo
def initialize(n)
raise ArgumentError, “Too many columns” if n > MAX_COLUMNS
@cols = n
end
end

If this value is not actually a constant, but might change at runtime
(e.g. from a command-line option), then you could use a
$global_variable, but I’d suggest a class instance variable.

class Foo
@max_columns = 30 # default value
def self.max_columns
@max_columns
end
def self.max_columns=(n)
@max_columns = n
end
end

Foo.max_columns = Integer(ARGV[0]) if ARGV[0]
puts Foo.max_columns

Note that class Foo is itself an object (of class Class), and so
@max_columns is an instance variable of the class itself.

Hi Brian,

This is perfect. Thank you very much!

Frank

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs