Last active
December 12, 2015 04:49
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
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?
Looks good overall -- testable and flexible, it seems.
Author
@shipstar: Separately. There's a wizard-ish flow, and these things are called in separate steps.
Author
@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
If you need keys as symbols tack on a
.symbolize_keystoo maybe?