Last active
December 10, 2015 04:38
-
-
Save svs/4382175 to your computer and use it in GitHub Desktop.
Showing a delegation pattern to handle fat models
This file contains hidden or 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
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