Skip to content

Instantly share code, notes, and snippets.

@mileszs
Last active December 12, 2015 04:49
Show Gist options
  • Select an option

  • Save mileszs/4717119 to your computer and use it in GitHub Desktop.

Select an option

Save mileszs/4717119 to your computer and use it in GitHub Desktop.
This is my refactored version of https://gist.github.com/mileszs/4709536. I am happier with it primarily because all of the parts are now in a single class for each major piece of functionality. It's much easier to understand; when you see in the controller `PagesGenerator.new(document).generate!`, you look in the PagesGenerator class, where you…
class CategoriesGenerator
def initialize(document, options = {})
@document = document
@master_categories = options[:master_categories] || MasterCategory.all
end
def generate!
@master_categories.each do |master_category|
@document.categories.build(wanted_attributes_from(master_category))
end
@document.save!
end
private
def wanted_attributes_from(master_category)
{
position: master_category.position,
name: master_category.name,
active: master_category.active,
master_category_id: master_category.id
}
end
end
class PagesGenerator
def initialize(document, options = {})
@document = document
end
def generate!
@document.categories.each do |category|
if category.pages.empty?
category.master_category.master_pages.each do |master_page|
category.pages.build(wanted_attributes_from(master_page))
end
category.save!
end
end
end
private
def wanted_attributes_from(master_page)
{
position: master_page.position,
name: master_page.name,
index_page: master_page.index_page,
master_page_id: master_page.id
}
end
end
@veloper
Copy link
Copy Markdown

veloper commented Feb 5, 2013

master_page.attributes.slice(*%w[position name index_page master_page_id])

If you need keys as symbols tack on a .symbolize_keys too maybe?

@shipstar
Copy link
Copy Markdown

shipstar commented Feb 5, 2013

Are these two classes being used in succession? e.g.

@document = Document.new
CategoryGenerator.new(@document).generate!
PagesGenerator.new(@document).generate!

Or are the uses separated in time/space?

@shipstar
Copy link
Copy Markdown

shipstar commented Feb 5, 2013

Looks good overall -- testable and flexible, it seems.

@mileszs
Copy link
Copy Markdown
Author

mileszs commented Feb 6, 2013

@shipstar: Separately. There's a wizard-ish flow, and these things are called in separate steps.

@mileszs
Copy link
Copy Markdown
Author

mileszs commented Feb 6, 2013

@veloper: Ah, thanks! What's sad is I was doing essentially that in the old one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment