Alias Model Name in Ruby

Suppose you want to rename a Ruby class name, but don’t want to go through the hassle of renaming all the files and class references in the code.  An easy solution is to alias the class (classes are just constants in Ruby).  If we have a BaseballPlayer class that we want to alias with Athlete, we can just set the BaseballPlayer constant equal to Athlete:

class BaseballPlayer
end
BaseballPlayer = Athlete

After the BaseballPlayer constant is aliased with Athlete, we can initialize BaseballPlayer objects with the Athlete keyword.

# This works
>> a = Athlete.new
# This also still works
>> b = BaseballPlayer.new

Aliasing a model with a class name that has a different meaning probably is not good, but this solution is good for classes that are renamed with a synonym (i.e. changing a Kid class to a Child class).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s