Daily Refactor #74: Extract Method in Invoice

The Refactoring

While adding tests to my Redmine Invoice plugin, I found the following nasty bit of logic.

Before

1
2
3
4
5
6
7
class Invoice < ActiveRecord::Base
 
  def self.open
    invoices = self.find(:all)
    return invoices.select { |invoice| !invoice.fully_paid? && !invoice.late? }
  end
end

After

1
2
3
4
5
6
7
8
9
10
11
12
13
class Invoice < ActiveRecord::Base
 
  def self.open
    invoices = self.find(:all)
    return invoices.select { |invoice| invoice.open? }
  end
 
  # Is this invoice current but not fully paid?
  def open?
    !fully_paid? && !late?
  end
 
end

Review

By using extract method, I created the #open? predicate which made the code (and tests) easier to read. I need to work on the finder inside Invoice#open next, since it’s selecting every Invoice record and filtering in Ruby.

Reference commit

Share

  • Facebook
  • Twitter
  • HackerNews
  • Reddit
  • Tumblr
  • Delicious
  • Email
  • RSS

Related posts:

  1. Redmine Refactor #140: Extract Method WikiController#edit to #update
  2. Redmine Refactor #118: Split Edit Method in NewsController
  3. Redmine Refactor #88: Extract Method from move and perform_move
  4. Daily Refactor #62: Extract Method in IssuesController
  5. Daily Refactor #38: Extract Method in StuffToDo

About Eric Davis

I founded Little Stream Software where I provide Redmine and ChiliProject services to help projects teams. I also created an ebook, Redmine Tips, were I show you how to become more productive using Redmine. I am also the author of Refactoring Redmine, where I go about refactoring Rails using Redmine as an example.

, , ,

Chirk HR     Reuse your existing job applicants »
WP Socializer Aakash Web