Write Software, Well

Refactoring: Extract Constructor to Base Controller

Since all controllers will need a constructor that accepts the env hash, it's better to pull it up in a base class. To stick to the Rails naming conventions, we'll call the base class ApplicationController.

Add the following code in controllers/application_controller.rb file.

# controllers/application_controller.rb

class ApplicationController
attr_reader :env

def initialize(env)
@env = env
end
end

Now our ArticlesController class can extend from this class and we can remove the redundant code.

# controllers/articles_controller.rb

require_relative 'application_controller'

class ArticlesController < ApplicationController
def index
'All Articles'
end
end

Restart the application and make sure everything is still working as expected.

Nice, clean, and tidy. We have a functioning controller structure which puts us well on the path to implementing views and generating dynamic HTML using the ERB gem, which we'll explore in the next post in the series.