3

I have a class that I want to reference by two different names when using it. The only way I can think to do this is.

class Entrance

  def open
    puts "the door is open"
  end

end

class Exit < Entrance
end

The thing is that in this example I want to represent that Entrance and Exit are the exact same thing, not that an Exit is a type of Entrance. Is there a better way to represent this?

1
  • Zach, after Exit = Entrance, you can have Entrance = nil or Entrance = SomethingElse (without affecting Exit), though Ruby will slap your hand with a warning that you've changed the definition of Entrance. Commented Jan 20, 2014 at 22:02

4 Answers 4

9

Easy and simple:

Exit = Entrance

Classes in Ruby are really just objects of class Class that are assigned to constants with their name. So, just have a new constant refer to the same object as the old constant.

Note that now Exit and Entrance are the exact same class, and anything you do to one happens to the other:

2.0.0p0 :009 > Exit.object_id == Entrance.object_id
 => true

Note: While this is possible, I'd think more carefully about your general architecture. Is their any difference between an Entrance and an Exit? Are they both just really Doors? Your architecture should be such that classes won't (usually) need to be aliased unless you have two synonymous names that you really want to use both, like Page and WebPage (I'd recommend against this too).

Sign up to request clarification or add additional context in comments.

5 Comments

Great Point, I'm building a test abstraction layer where two classes do really do the exact same thing. This would make it easier for less technical types to troubleshoot tests. The real world use is 'Add' and 'Edit' for a type of resource.
@Zach: That seems unclear to me. Shouldn't add add a new resource, and edit only edit existing ones?
Yes, but in automating the page the elements are exactly the same. Once you get to the form that either adds or edits the resource the only difference in the application I am testing is heading on the top of the page and the URL.
@Zach: Ok. Just remember that there is no way to distinguish between Add and Edit using this technique.
Thats exactly what I want, Thanks
3

In Ruby classes are also Object. So you can do as below :

Exit = Entrance

Remember that doesn't mean your class Entrance have now another name which is Exit. Rather Exit is a constant, which is now holding the reference to you class object Entrance.

 Entrance.name # => "Entrance"
 Exit.name # => "Entrance"
 Exit.object_id == Entrance.object_id # => true

Comments

2

You can assign a constant name like anything else.

class Entrance; end
Exit = Entrance

Comments

0

Maybe add new class - Door. Exit < Door, Entrance < Door.

1 Comment

This doesn't answer the question given. -1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.