nsmmrs.net

Defining Class and Module Aliases in Ruby and Rails

In Ruby, creating a new name for an existing value is easy:

a = 1
b = a

b #=> 1

Since Ruby module names are just constants (and classes are just special modules), you can treat them the same way:

class OriginalName
end

NewName = OriginalName

NewName.new #=> #<OriginalName:0x00007ffdb0a59190>

In a Rails application, constants are expected to be defined in a file with a corresponding path and name (otherwise, the auto-loader will have trouble finding it).

For example, the following model

class Nested::OriginalName < ApplicationRecord
end

would conventionally be defined in:

app/models/nested/original_name.rb

The alias, Nested::NewName, would ideally be defined in:

app/models/nested/new_name.rb

For example:

Nested::NewName = Nested::OriginalName

It’s more likely, though, that you would be looking for a shorter alias, without the namespace. As long as you follow the file path and name conventions, you can safely define any alias you want:

# app/models/new_name.rb

NewName = Nested::OriginalName
Software developer and art hobbyist living in Dallas, TX.