DEV Community

Noah Summers
Noah Summers

Posted on • Originally published at on

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

NewName = OriginalName #=> #<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

would conventionally be defined in:


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


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

Top comments (0)