Split Padrino Controllers

Some things are bigger the better. But some, when they are big, are truly ugly! Code makes the top of that list. I recently opened a Padrino class with 2900+ lines of pure spaghetti. It was traumatic to touch that file that had countless number of actions in it.

Making an admin section? Wondering how to avoid writing every thing in app/controllers/admin.rb? Well you are of luck and the approach is really simple.

Xygen is not its real name.

# file: app/controllers/admin/products.rb
class Xygen::App.controllers :admin do
  layout :admin

  get '/products' do
    @products = Product.all
    render 'admin/products/index'
  end

  # get '/products/:id' do
  # end
  # and so on...
end

Now that you are splitting code in to files, you might wonder where to add common code.

There are few places you can add them to.

  1. Helpers (my preferred)
  2. app.rb (lets keep that slim too, shall we?)
# file: app/helpers/admin.rb
class Xygen::App.helpers do
  def authenticate
    # your foo doo
  end
end

And finally use it in your codeā€¦

# file app/controllers/admin/products.rb
class Xygen::App.controllers :admin do
  before { authenticate }
  # rest of the code ...
end