Skip to content

Instantly share code, notes, and snippets.

@svs
Last active December 10, 2015 04:38
Show Gist options
  • Save svs/4382175 to your computer and use it in GitHub Desktop.
Save svs/4382175 to your computer and use it in GitHub Desktop.
Showing a delegation pattern to handle fat models
require 'forwardable'
class User
extend Forwardable
attr_accessor :view_delegate_class
def_delegators :view_delegate, :full_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
# if we set @view_delegate_class, we can override which class we use to show the full name
# thus we can inject a dependency and at runtime choose the class to delegate to.
def view_delegate
(@view_delegate_class || UserViewDelegate).new(self)
end
end
class UserViewDelegate
def initialize(user)
@user = user
end
def full_name
"#{first_name} #{last_name}"
end
# any method not defined here is going to be called on the @user.
# normally, since these classes are extracted from larger classes, it saves us
# having to say @user.first_name, @user.last_name, etc.
# also, there it protects us from changes to the User class if we don't repeat the API here.
def method_missing(name, *args)
@user.send(name, *args)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment