0

I'm following along a tutorial to make a Rack-based app:

require 'forwardable'
module Eldr
  class App
    class << self
      extend Forwardable
      attr_accessor :builder
      def_delegators :builder, :map, :use

      def builder
        @builder ||= Rack::Builder.new
      end
    end
  end
end

I know this will sound really noobish, but I'm new to Ruby metaprogramming:

  • What exactly is the class << self? Doesnt that mean App < App?
  • What exactly is Forwardable? I looked it up but I'm sad to say I don't understand it still
  • Why is app extending Forwardable and what is Forwardable?

I know that the goal is to make this bit behave like Rack::Builder; Just trying to wrap my head around this one.

Thanks in advance.

dsp_099
  • 5,801
  • 17
  • 72
  • 128
  • Please, if you have three questions, ask three questions, not one. For example, your question about `class << foo` has already been asked and answered on StackOverflow, but because of the other two questions with which it is intermingled, it cannot be linked as a duplicate. – Jörg W Mittag Jul 31 '15 at 22:32

1 Answers1

2

What exactly is the class << self? Doesnt that mean App < App?

No, the syntax class << self lets you modify the metaclass of an object (in this case self). There is a great answer that explains this here: class << self idiom in Ruby

What exactly is Forwardable? I looked it up but I'm sad to say I don't understand it still.

The Forwardable module allows methods send to one object to be redirected to the result of calling a method on that object. In this case, methods sent to Eldr::App will be redirected to Eldr::App.builder. So when you call Eldr::App.map, you are actually calling Eldr::App.builder.map.

Why is app extending Forwardable?

The extend Forwardable line adds Forwardable to the list of ancestors of Eldr::App's metaclass. This is done just because that's how forwardable was designed to be used. Here is a link to Forwardable's documentation. It has some examples of what Forwardable is and how to use it.

Community
  • 1
  • 1
Adrian
  • 14,931
  • 9
  • 45
  • 70