Search code examples
rubycamping

What is Camping 'meta_def' doing?


In one of the first lines of camping.rb: https://github.com/camping/camping/blob/ae5a9fabfbd02ba2361ad8831c15d723d3740b7e/lib/camping-unabridged.rb#L17,

The framework adds the meta_def method to the Object class. I've been playing around with this bit of code and I still can't understand what it's doing.

class Object #:nodoc:
  def meta_def(m,&b) #:nodoc:
    (class<<self;self end).send(:define_method,m,&b)
  end
end

When I try printing (class<<self;self end) like this:

class Object #:nodoc:
  def meta_def(m,&b) #:nodoc:
    puts (class<<self;self end)
  end
end

puts 'a'.meta_def 'boo'

It prints out #<Class:#<String:0x146810>>, which means it's making an instance of Class. However, I still don't know what exactly it is and what (class<<self;self end) did. Can someone explain how this works?


Solution

  • class Object 
      def meta_def(m,&b) 
        (class<<self;self end)
      end
    end
    ob = 'a'
    ob.meta_def 'boo' # => #<Class:#<String:0x94daf54>>
    ob.singleton_class # => #<Class:#<String:0x94daf54>
    

    I still don't know what exactly it is and what (class<<self;self end) did.

    Your code is creating the singleton_class of the receiver('a') of the method meta_def.Now look below :

    class Object #:nodoc:
      def meta_def(m,&b) #:nodoc:
        (class<<self;self end).send(:define_method,m,&b)
      end
    end
    ob = 'foo'
    ob.meta_def(:meth) {"Welcome"}
    ob.meth # => "Welcome"
    

    Now in the above code, what the line is doing?

    As said above it is creating first a singleton class for the receiver.Then using define_method, a method named :meth with a body containing only one line "Hello" is created for the receiver singleton class.