1

I am building a modular Padrino application to mount mutiple applications.

I am mounting a base application to /

class BaseApp < Padrino::Application
  ...
end

I am then mounting other appilications to other endpoints, such as /clients and these applications inherit from the base application:

class ClientsApp < BaseApp
  ...
end

This inheritence allows me to define all my settings, error handling and any included rack middleware in the app.rb for the BaseApp class.

So far so good. But I would also like to share before and after routing between apps. For example in my BaseApp controller code I want to do this:

BaseApp.controller do
  before do
    ...
  end
  after do
    ...
  end

  get :index do
    ...
  end
end

Rather than repeating these filters in my ClientsApp controller code, like so:

ClientsApp.controller do
  before do
    ...
  end
  after do
    ...
  end

  get :index do
    ...
  end
end

Is there anyway I can DRY up this code and specify the filters once in BaseApp and have them somehow inherited? I understand these filters are methods calls rather than methods.

Thanks!

Ciaran Archer
  • 12,316
  • 9
  • 38
  • 55

1 Answers1

4

You can use standard sinatra extensions, put under lib:

# lib/common_filters.rb
module CommonFilters
  def self.registered(app)
    app.before do
      ...
    end

    app.after do
      ...
    end
  end
end

Then in yours apps:

# app/app.rb
class MyApp < Padrino::Application
  register CommonFilters
end
DAddYE
  • 1,719
  • 11
  • 16
  • Thanks but doesn't work - `NoMethodError: undefined method 'filters=' for ClientsApp:Class` – Ciaran Archer Feb 03 '12 at 14:42
  • Thanks. Updated code doesn't throw an error anymore, but all routes in subclass application now return a 404. It's as if the routes are being overwritten/lost or something. Any other ideas? – Ciaran Archer Feb 06 '12 at 16:42
  • Works great, I need to register the `CommonFilters` with each of my apps, but this is pretty DRY so I'm happy. Thanks!! – Ciaran Archer Feb 07 '12 at 08:57