Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Meta Programming Question

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?

like image 804
ottobar Avatar asked Oct 10 '08 14:10

ottobar


People also ask

Does Ruby support meta programming?

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.

What is Ruby meta programming?

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.

What is the difference between extend and include in Ruby?

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.

What is method missing in Ruby?

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.


1 Answers

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.

like image 142
David Nehme Avatar answered Sep 28 '22 02:09

David Nehme