mileszs
2/4/2013 - 8:36 PM

Each document instance has categories and pages that are generated from "master categories" and "master pages". I think a refactor is in ord

Each document instance has categories and pages that are generated from "master categories" and "master pages". I think a refactor is in order. I would like to compare my result with the thoughts of others. How would you refactor this code (if you would refactor it)?

class Category < ActiveRecord::Base
  belongs_to :document
  belongs_to :master_category

  has_many :pages

  def generate_pages!
    if pages.empty?
      master_category.master_pages.each do |master_page|
        pages.create!(master_page.page_attributes)
      end
    end
    self.save!
  end

end
class Document < ActiveRecord::Base
  has_many :categories
  has_many :master_categories, through: :categories
  has_many :pages, through: :categories

  def generate_categories!
    MasterCategory.all.each do |master_category|
      self.categories.create!(master_category.category_attributes)
    end
  end

  def generate_pages!
    self.categories.each do |category|
      category.generate_pages!
    end
  end

end
class MasterCategory < ActiveRecord::Base
  has_many :categories
  has_many :master_pages

  def category_attributes
    self.attributes.slice('position', 'name').merge(master_category_id: self.id)
  end
end
class MasterPage < ActiveRecord::Base
  belongs_to :master_category
  has_many :pages

  def page_attributes
    self.attributes.slice('position', 'name', 'index_page').merge(master_page_id: self.id)
  end
end