Skip to content

Instantly share code, notes, and snippets.

@dinobi
Last active January 26, 2019 10:40
Show Gist options
  • Select an option

  • Save dinobi/1978914b87ecbc5f930b4b0441df1376 to your computer and use it in GitHub Desktop.

Select an option

Save dinobi/1978914b87ecbc5f930b4b0441df1376 to your computer and use it in GitHub Desktop.
Using delegation pattern to refactor fat ActiveRecord models
# Using Delegation Pattern
class Product < ActiveRecord::Base
# instead of defining a notes method inside Product class
# where we can perform some arbitrary logic on user notes,
# we can simply delegate the note method to the UserNote class
#
# USAGE: product.user_note
delegate :note, to: :user_note, prefix: :user
end
class UserNote < ActiveRecord::Base
def note
# logic for manipulating user notes for objects goes here
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment