Last active
December 20, 2015 13:48
-
-
Save saturnflyer/6141054 to your computer and use it in GitHub Desktop.
Maybe get values from an object. Wrap one object, but check if an alternate one has better data first. In this case, we wrap a user object, but for the methods we specify we can check the profile object for data before falling back to the user.
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
require 'delegate' | |
class SpecialFormatter < SimpleDelegator | |
def initialize(user, profile) | |
super(user) | |
@profile = profile | |
end | |
attr_reader :profile | |
def self.maybe(*names) | |
options = names.last.is_a?(Hash) ? names.pop : {} | |
accessor = options.fetch(:from) | |
names.each do |name| | |
define_method(name) do | |
from = self.send(accessor) | |
(!from.nil? && from.respond_to?(name) && from.public_send(name)) || __getobj__.public_send(name) | |
end | |
end | |
end | |
maybe :first_name, :last_name, :email, from: :profile | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment