![]() The point is: while both lookup algorithms look for definitions in the ancestors of the current class, they differ in how they determine which class counts as “the current class”. For method lookup the current class (the first class in the ancestor chain Ruby will traverse in search of a definition) is the receiver’s class. This is the same lookup behavior that caused #foo_via_method to succeed. Ruby is able to resolve OtherSubClass::NAME even though that constant is not defined in OtherSubClass, but rather in its superclass, MyOtherClass. Why don’t constants behave the same way? Constant lookupĪs with methods, Ruby is also able to look through the superclass chain to find constants. If it gets all the way to BasicObject and strikes out, it invokes #method_missing. How Ruby evaluates that method call? Look for a definition of #foo_via_method in SubClass‘s superclass, M圜lass. Ruby looks in the receiver’s class for the method definition, and if it can’t find it, Ruby iterates up the superclass chain (also known as the “ancestor chain”) until it finds a class that implements the method. Why does the version that uses a method work but the version that uses the constant fail? Method lookup The version that refers to a method in the subclass returns the desired value, but the version that refers to a constant in subclass throws an error. # NameError: uninitialized constant M圜lass::FOO_CONSTANT ![]() An example that distills the structure of the code: class M圜lass The method he changed into a constant is defined in one class but is called from within its superclass. ![]() And, surprisingly, the code that was calling the constant couldn’t find it even though it was able to find a method in the same context. He has noticed that story_boolean method always returns a static value, so Michael wondered if it should be the constant instead of a method. One day Michael Hoffman, the author of the original article, was doing a refactor of a controller. By this, you will benefit and upgrade your skills! So even if you think you know everything, maybe you’ll find something new in our article about how to define constants in Ruby. You can be a superb professional, but to upgrade your knowledge you have to read more non-stop. Syndicode is still looking for Ruby on Rails developer and continues the series of useful articles about Ruby and Ruby on Rails tricks, hacks, performance etc. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |