Redmine Refactor #130: Extract Method TimelogController#edit to TimelogController#new

Yesterday’s refactoring of TimelogController#edit took care of it’s first action. Now I need to use extract method again to pull out the “save new TimeEntry” action (#create).

Before

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class TimelogController  [:new, :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
25
26
27
28
29
30
31
class TimelogController  [:new, :create, :edit, :destroy]
 
  verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed }
  def create
    @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 @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
 
  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

Just like last time, this refactoring didn’t actually make any impact on the #edit method at all. #edit still needs all of the code to handle it’s last two actions (show a form for existing TimeEntries and update existing TimeEntries). At least there is only one more refactoring before #edit is completely split up. Then I can finally start removing code.

Reference commit