Now that IssuesController, ProjectsController, and VersionsController have been refactored to resources, I’m moving on to the NewsController. This controller suffers from the same problem that the other ones did, using the #new and #edit actions for two different purposes. Using split method, I can start to separate these actions and start to convert NewsController to a REST resource.
Before
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class NewsController [:new, :index, :preview] before_filter :find_project_from_association, :except => [:new, :index, :preview] before_filter :find_project, :only => [:new, :preview] before_filter :authorize, :except => [:index, :preview] before_filter :find_optional_project, :only => :index accept_key_auth :index def new @news = News.new(:project => @project, :author => User.current) if request.post? @news.attributes = params[:news] if @news.save flash[:notice] = l(:notice_successful_create) redirect_to :controller => 'news', :action => 'index', :project_id => @project end end end |
After
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class NewsController [:new, :create, :index, :preview] before_filter :find_project_from_association, :except => [:new, :create, :index, :preview] before_filter :find_project, :only => [:new, :create, :preview] before_filter :authorize, :except => [:index, :preview] before_filter :find_optional_project, :only => :index accept_key_auth :index def new @news = News.new(:project => @project, :author => User.current) end def create @news = News.new(:project => @project, :author => User.current) if request.post? @news.attributes = params[:news] if @news.save flash[:notice] = l(:notice_successful_create) redirect_to :controller => 'news', :action => 'index', :project_id => @project else render :action => 'new' end end end |
In order for this refactoring to work, I had to duplicate the @news setup in #create. I’m not worried about removing that duplication yet because a simple extract method or two will fix it. NewsController‘s #edit method still needs to be refactored and there are several commenting methods that should be refactored also.