Today I Learned

hashrocket A Hashrocket project

How Sinatra avoids polluting inheritance chain

When you open a new file:

[13] pry(main)> self
=> main
[14] pry(main)> self.class
=> Object

main is an instance of Object

An example: the Sinatra DSL

require 'sinatra'

get '/' do
  'Hello world!'
end

#get is put in main's singleton class

[1] pry(main)> require 'sinatra'
=> true
[2] pry(main)> method(:get).source_location
=> .../sinatra-1.4.6/lib/sinatra/base.rb", 1987]
pry(main)> Object.new.get
NoMethodError: undefined method `get' for #<Object:0x007fc423d9ec18>

This is achieved by extending the singleton class of main.

from Sinatra:

extend Sinatra::Delegator

A simple example:

class Foo
  module DSL
    def foo
      'bar'
    end
  end
end

extend ::Foo::DSL
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.