Skip to content

Instantly share code, notes, and snippets.

@saturnflyer
Last active December 20, 2015 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saturnflyer/6141054 to your computer and use it in GitHub Desktop.
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.
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