Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to “split” up a large Rails controller

I currently have an already-large controller that’s getting bigger. I was wondering what would be the best way to slim down my controllers. I’m not necessarily looking for the easiest way, but a safe and efficient way. I’ve been developing with Rails for a while now but I’m still not familiar with how “subclassing” works and I’m not even sure if it’s supposed to be used in this way. I was thinking maybe something like this?

class SomeController < ApplicationController
end

class MoreFunctionsController < SomeController
end

That’s currently untested – I’m still working on it right now – but I hope that this would sort of give you an idea of what direction I’m trying to go. I’m also not sure how the routing for this would look. What would be the best way to “split” up a large controller?

like image 828
goo Avatar asked Sep 11 '13 15:09

goo


1 Answers

ActiveSupport::Concern (documentation) is what you are looking for.

Update

Something like this:

# config/application.rb
config.autoload_paths += %W(#{Rails.root}/app/controllers/concerns) # in Rails4 this is automatic

# app/controllers/my_controller.rb
class  MyController < ApplicationController
  include GeneralStuffConcern

  def index
    render text: foo
  end
end

# app/controllers/concerns/general_stuff_concern.rb
module GeneralStuffConcern
  extend ActiveSupport::Concern
  
  def show
    redirect_to root_path
  end
  
protected
  def foo
    'fooo'
  end
end

update 2

I actually recommend this more http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

update 3 (2022)

Bounded contexts https://blog.eq8.eu/article/rails-bounded-contexts.html

like image 72
equivalent8 Avatar answered Oct 15 '22 09:10

equivalent8