Created
January 8, 2016 17:43
-
-
Save maxcodes/a711e618db6a9f3e1a39 to your computer and use it in GitHub Desktop.
Refactoring blocks
This file contains 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 Book < ActiveRecord::Base | |
has_many :shelf_books | |
has_many :shared_items, as: :item | |
has_many :book_reviews | |
end | |
class ShelfBook < ActiveRecord::Base | |
belongs_to :book | |
end | |
class SharedItem < ActiveRecord::Base | |
belongs_to :item, polymorphic: true | |
end | |
class BookReview < ActiveRecord::Base | |
belongs_to :book | |
end |
This file contains 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
def update_associated_records(old_book, new_book) | |
update_shelf_books(old_book, new_book) | |
update_shared_items(old_book, new_book) | |
update_reviews(old_book, new_book) | |
end | |
def update_shelf_books(old_book, new_book, &block) | |
old_book.shelf_books.map { |shelf_book| shelf_book.update(book: new_book) } | |
end | |
def update_shared_items(old_book, new_book) | |
old_book.shared_items.map { |shared_item| shared_item.update(item: new_book) } | |
end | |
def update_reviews(old_book, new_book) | |
old_book.book_reviews.map do |review| | |
review.update(book: new_book) | |
update_associated_activity(review) # this is the only part different from the others | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment