I was looking at the Ruby logging library Logging.logger method and have a question from the source at github relating to this piece of code:
logger = ::Logging::Logger.new(name)
logger.add_appenders appender
logger.additive = false
class << logger
def close
@appenders.each {|a| a.close}
h = ::Logging::Repository.instance.instance_variable_get :@h
h.delete(@name)
class << self; undef :close; end
end
end
I understand that the class << logger opens up the eigen/meta/singleton class to the logger object to add an instance specifice close method. However, I am not exactly sure what the "class << self; undef :close; end" does and for what purpose. Can anyone tell me what it means?
MetaProgramming gives Ruby the ability to open and modify classes, create methods on the fly and much more. A few examples of metaprogramming in Ruby are: Adding a new method to Ruby's native classes or to classes that have been declared beforehand. Using send to invoke a method by name programmatically.
Metaprogramming is a technique by which you can write code that writes code by itself dynamically at runtime. This means you can define methods and classes during runtime.
In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.
method_missing is a method that ruby gives you access inside of your objects a way to handle situations when you call a method that doesn't exist. It's sort of like a Begin/Rescue, but for method calls. It gives you one last chance to deal with that method call before an exception is raised.
this actually deletes the method (when it actually gets executed). It's a safeguard to make sure close is not called twice. It kind of looks like there are nested 'class << ' constructs, but there aren't. The inner class << is executed when the method is called and the outer class << is called when the method is defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With