THE @APP OBJECT
...or how to separate your application
from Rails, live longer and prosper
by Hubert Łępicki
@hubertlepicki
Why @app object?
- You want to build your application, not Rails
- You might decide to get rid of Rails at some point
- You want to use the same logic from different places
- You want to make your integration tests easier to write
- You want to hide classes and their implementation
The only rule of @app object
Never call it @app
Give it meaningful name
Example names
- @blog
- @shop
- @intranet
- @cms
- @player
The root object
class ApplicationController < ActiveSomething
helper_method :intranet
def intranet
@intranet ||= Intranet.new(current_user)
end
end
One root to rule them all
class DashboardController
helper_method :dashboard
def dashboard
@dashboard ||= intranet.dashboard
end
def show
@visits = dashboard.visits.paginate ...
end
end
Multiple layers of objects
class Intranet
def dashboard; @dashboard ||= Dashboard.new
end
class Dashboard
def stats
@stats ||= DashboardStats.new
end
end
Nobody cares what classes your objects are
class FilesController < ApplicationController
def new
@form_model = intranet.files.form
end
end
Assemble custom @app for the user
class Intranet
def initialize(user)
@employee = user
end
def files
@files ||= if user.is_a?(Admin)
FilesManager.new
else
FilesViewer.new
end
end
end
Authorization without authorization
class FilesViewer
def files_list
end
end
class FilesBrowser < FilesViewer
def upload_file(file)
end
def remove_file(filename)
end
end
Easier integration tests
- Testing with real browser is hard and slow
- Write just some end-to-end tests, leave edge cases
for integration tests - Write more integration tests easier
The @app object
By Hubert Łępicki
The @app object
- 1,763