Leo Leo - 7 days ago 7
Ruby Question

Why constants are not recommended in the class of ruby?

It seems that it is a protocol to write a class this way when you have some constants to add:

module AddressValidator
FIELD_NAMES = [:street, :city, :region, :postal_code, :country]
VALID_VALUE = /^[A-Za-z0-9\.\# ]+$/
class << self
...
end
end


To add constants in the class also work, but why it is not recommended?

class AddressValidator
FIELD_NAMES = [:street, :city, :region, :postal_code, :country]
VALID_VALUE = /^[A-Za-z0-9\.\# ]+$/

...
end

Answer

I think you might be a bit confused.

The first example you have does not create a class.

class << self

This is the notation for opening the singleton class of the current object in scope (in the case of your example, the AddressValidator).

You can test this by calling AddressValidator.new and not getting an AddressValidator instance, but a NoMethodError.

I think what you may have heard is about namespacing constants, which does use Modules as a standard practice.

If you just have a bunch of constants that you want to separate with a namespace using a module like this is better than using a class. Basically, the rule of thumb is use modules for namespacing and classes only if you want to create instances of that class.