Skip to content

Instantly share code, notes, and snippets.

@CodeOfficer
Created February 25, 2009 17:48
Show Gist options
  • Save CodeOfficer/70314 to your computer and use it in GitHub Desktop.
Save CodeOfficer/70314 to your computer and use it in GitHub Desktop.
jays presenter pattern
# from: http://pastie.org/47453
# http://blog.jayfields.com/2007/03/rails-presenter-pattern.html
class CompletePresenter < Presenter
presentable :account, UserAccount.new
presentable :address, Address.new
presentable :credential, UserCredential.new
def save
account.save && address.save && credential.save
end
end
class Presenter
def initialize(params)
params.each_pair { |attribute, value| self.send :"#{attribute}=", value } unless params.nil?
end
def self.presentable(name, instance)
presentables[name.to_sym] = instance
define_method name do
instance
end
end
def self.presentables
@presentables ||= {}
end
def method_missing(sym, *args)
super unless presentable?(sym)
receiver, message = parse_method(sym)
receiver.send message, *args
end
def presentable?(method_name)
self.class.presentables.has_key? method_name.to_s.split("_").first.to_sym
end
def parse_method(method_name)
receiver_key, *method_to_call_parts = method_name.to_s.split("_")
[self.class.presentables[receiver_key.to_sym], method_to_call_parts.join("_").to_sym]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment