Skip to content

Instantly share code, notes, and snippets.

@LNA
Last active January 1, 2016 06:59
Show Gist options
  • Save LNA/8108957 to your computer and use it in GitHub Desktop.
Save LNA/8108957 to your computer and use it in GitHub Desktop.
Refactoring code smells. Refactoring an Active Record Relationship Model
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