Artem Kalinchuk
Artem Kalinchuk

Reputation: 6652

How do I name a Rails ruby file whose class name has numbers?

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

Answers (4)

lulalala
lulalala

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

bmalets
bmalets

Reputation: 3297

Try to do this:

  • rename your model and model.rb file
  • add table_name magic

as here:

class TwoProduct < ActiveRecord::Base
  self.table_name = '2_products'
end

Upvotes: 1

rupweb
rupweb

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

Ry-
Ry-

Reputation: 224886

Yes, Ruby class names may contain numbers. However, as with all identifiers in Ruby, they may not begin with numbers.

Reference:

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

Related Questions