Skip to content

Instantly share code, notes, and snippets.

@maxcodes
Created January 8, 2016 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxcodes/a711e618db6a9f3e1a39 to your computer and use it in GitHub Desktop.
Save maxcodes/a711e618db6a9f3e1a39 to your computer and use it in GitHub Desktop.
Refactoring blocks
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
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