Redmine Refactor #131: Extract Method TimelogController#edit to TimelogController#update

Finally, today I was able to refactor enough of TimelogController in order to start removing the extra code from #edit. Using extract method I pulled out the #update method that will perform the actual database saves for a TimeEntry.

Before

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class TimelogController  [:new, :create, :edit, :destroy]
 
  def edit
    (render_403; return) if @time_entry && !@time_entry.editable_by?(User.current)
    @time_entry ||= TimeEntry.new(:project => @project, :issue => @issue, :user => User.current, :spent_on => User.current.today)
    @time_entry.attributes = params[:time_entry]
 
    call_hook(:controller_timelog_edit_before_save, { :params => params, :time_entry => @time_entry })
 
    if request.post? and @time_entry.save
      flash[:notice] = l(:notice_successful_update)
      redirect_back_or_default :action => 'index', :project_id => @time_entry.project
      return
    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
24
class TimelogController  [:new, :create, :edit, :update, :destroy]
 
  def edit
    (render_403; return) if @time_entry && !@time_entry.editable_by?(User.current)
    @time_entry.attributes = params[:time_entry]
 
    call_hook(:controller_timelog_edit_before_save, { :params => params, :time_entry => @time_entry })
  end
 
  verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
  def update
    (render_403; return) if @time_entry && !@time_entry.editable_by?(User.current)
    @time_entry.attributes = params[:time_entry]
 
    call_hook(:controller_timelog_edit_before_save, { :params => params, :time_entry => @time_entry })
 
    if @time_entry.save
      flash[:notice] = l(:notice_successful_update)
      redirect_back_or_default :action => 'index', :project_id => @time_entry.project
    else
      render :action => 'edit'
    end    
  end
end

Since #update handles saving the TimeEntry, I was able to remove entire save section of code from #edit. Also since #edit is only used on existing records, I removed the conditional initialization too (@time_entry ||= TimeEntry.new(...)). Now I think TimelogController is ready to be converted to a REST resource.

Reference commit