Reputation: 6652
Can a Rails class name contain numbers? For example:
class Test123
end
Is this a valid class? I get an uninitialized constant Test123
error when I try to load the class.
Upvotes: 21
Views: 11346
Reputation: 17981
I think Artem Kalinchuk's last comment deserves to be the answer of this misworded question.
A Ruby class name can contain numbers.
A Rails class has to be defined in a correctly named file. If I define a class called NewYear2012Controller
:
Correct file name: new_year2012_controller.rb
Incorrect file name: new_year_2012_controller.rb
(note the extra underscore)
Because this is how Rails inflector and auto-loading works.
Upvotes: 64
Reputation: 3297
Try to do this:
as here:
class TwoProduct < ActiveRecord::Base
self.table_name = '2_products'
end
Upvotes: 1
Reputation: 3328
I don't know about this...
See the following
class Ab123
def initialize(y)
@z = y
end
end
class AbCde
def initialize(y)
@z = y
end
end
and the following instantiations:
Ab123.new x
or
AbCde.new x
Only the latter AbCde.new x
instantiates properly.
Upvotes: 0
Reputation: 224886
Yes, Ruby class names may contain numbers. However, as with all identifiers in Ruby, they may not begin with numbers.
Identifiers
Examples:
foobar ruby_is_simple
Ruby identifiers are consist of alphabets, decimal digits, and the underscore character, and begin with a alphabets(including underscore). There are no restrictions on the lengths of Ruby identifiers.
Upvotes: 7