Renaming class in Ruby (a kinda)
Lets say that you have a situation where you need to code about dogs. You know that there are different kind of dogs and you end up with a code structure as shown
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module Animal
module Domestic
class Dog
def sound
"woof"
end
end
end
module Wild
class Dog
def sound
"grrr"
end
end
end
end
So there are two kinds of dogs, one is wild that can be accessed like
Animal::Wild::Dog
and other one is
Domestic which could be accessed in similar way.
So if you want to print out how Domestic and Wild dog sounds like you can write a program as shown:
1
2
3
4
5
6
7
8
# using_dog_in_animal_module.rb
require_relative "dog_in_animal_module.rb"
include Animal
puts Domestic::Dog.new.sound
puts Wild::Dog.new.sound
But if you look I am using something like this Domestic::Dog.new.sound
which is
long to code and tax my fingers, what if I could do something that would make
my typing shorter? Fortunately you can do that in Ruby. See the program below:
1
2
3
4
5
6
7
8
9
# renaming_class.rb
require_relative "dog_in_animal_module.rb"
DomesticDog = Animal::Domestic::Dog
WildDog = Animal::Wild::Dog
puts DomesticDog.new.sound
puts WildDog.new.sound
In the code above, notice line 5 and line 6, we are kinda reaming the class.
Rather using the long form Animal::Domestic::Dog
we simply assign it to a constant name DomesticDog
as shown
DomesticDog = Animal::Domestic::Dog
and
in line 8 we can use it short like puts DomesticDog.new.sound
.
In a large programming environment, we would have reduced lot of typing. Happy coding! :)
Notes