Class alias in Ruby
Classes don't have names in Ruby. They are just objects assigned to variables, just like any other object. If you want to refer to a class via a different variable, assign it to a different variable:
Foo = String
in file coupon.rb:
class Coupon #...end# add this line of code to make alias for class names# option1. if you haven't defined a "Ticket" class: Ticket = Coupon # option2. if Ticket has been defined, you have to redefine it: Object.send :remove_const, "Ticket"const_set "Ticket", Coupon
"Any referrence that begins with an uppercase letter, including the names of classes and modules, is a constant" -- << metaprogramming ruby>>, page38, Constant section
Anyone coming here looking for how to alias a rails model class to have a new name:
I was able to simply do Foo = Bar
, but had to put Foo
inside it's own model file so that I wouldn't get a Uninitialized Constant Error. e.g.
# models/foo.rbFoo = Bar
Also you may find weirdness trying to use the alias in associations like has_many
, has_one
etc. I've found you can usually get around those by using the root namespace (or appropriate namespace depending on how your models are structured) to make sure Rails is trying to autoload the right constant:
has_many :foo, class_name: '::Foo'