Last active
January 1, 2016 06:59
-
-
Save LNA/8108957 to your computer and use it in GitHub Desktop.
Refactoring code smells. Refactoring an Active Record Relationship Model
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
module AR | |
class Guest < ActiveRecord::Base | |
has_many :orders, class_name: "Orders" | |
has_many :drinks, through: :orders, class_name: "Orders" | |
def drinks | |
drinks_array = [] | |
AR::Orders.all.each do |relationship| | |
if relationship.guest_id == self.id | |
drinks_array << relationship.drink | |
end | |
end | |
drinks_array | |
end | |
end | |
end | |
Code Smells: | |
1. Need to DRY out code. class_name: "Orders" appears twice. | |
2. The drinks method is too long. | |
3. The drinks method is conditionally complex; we can simplify the if logic block and make it easier to read. | |
4. Law of Delimeter ??? Something about neighbors. | |
Becomes: | |
module AR | |
class Guest < ActiveRecord::Base | |
has_many :ordes, class_name: "Orders" | |
def drinks | |
AR::Orders.where("guest_id = ?", self.id).map do |relationship| | |
relationship.drink | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment