Daily Refactor #69: Inline Temp in SourceNews#migrate

I wanted to start refactoring my Redmine merge plugin now. I’m getting it ready for a release so doing a few refactorings now will help me make sure it’s working properly.

The Refactoring

Using inline temp I was able to clean up how the SourceNews#migrate converts data from one database to the other database.

Before

1
2
3
4
5
6
7
8
9
10
11
12
class SourceNews  'SourceUser', :foreign_key => 'author_id'
 
  def self.migrate
    all.each do |source_news|
      n = News.new
      n.attributes = source_news.attributes
      n.project = Project.find(RedmineMerge::Mapper.get_new_project_id(source_news.project_id))
      n.author = User.find_by_login(source_news.author.login)
      n.save!
    end
  end
end

After

1
2
3
4
5
6
7
8
9
10
11
class SourceNews  'SourceUser', :foreign_key => 'author_id'
 
  def self.migrate
    all.each do |source_news|
      News.create!(source_news.attributes) do |n|
        n.project = Project.find(RedmineMerge::Mapper.get_new_project_id(source_news.project_id))
        n.author = User.find_by_login(source_news.author.login)
      end
    end
  end
end

Review

Since SourceNews#migrate was a pretty simple method, this refactoring is easy to understand. By using the block method of ActiveRecord#create! I don’t have to worry about calling #save! at the end. It’s also a nice and simple way to keep all of the News construction in places (inside the block).

Reference commit

Share

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

Related posts:

  1. Daily Refactor #75: Inline Temp in Invoices#outstanding
  2. Daily Refactor #70: Inline Temp in SourceVersion#migrate

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