Created
October 7, 2009 19:43
-
-
Save reinh/204366 to your computer and use it in GitHub Desktop.
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
# Encapsulates presentation and representation information for database objects | |
# by wrapping them in a presentation layer. Proxies data requests to the data object | |
# itself for transparency. | |
# | |
# Subclasses allow for customization | |
# | |
# ORM-agnostic | |
# | |
# sample use: | |
# class PostPresenter < PresenterProxy | |
# hidden_attribtes += [ :updated_at, :version, :deleted_at ] | |
# end | |
# | |
# class PostController < ApplicationController | |
# def index | |
# @posts = Post.all.map(&PostPresenter) | |
# | |
# respond_to do |format| | |
# format.html | |
# format.xml { render => @posts.to_xml } | |
# format.js { render => @posts.to_json } | |
# end | |
# end | |
# | |
# def show | |
# @post = Post.find(params[:id]).map(&PostPresenter) | |
# | |
# respond_to do |format| | |
# format.html | |
# format.xml { render => @post.to_xml } | |
# format.js { render => @post.to_json } | |
# end | |
# end | |
# | |
# end | |
class PresenterProxy | |
# TODO: better method mask | |
instance_methods.each { |meth| undef_method(meth) unless meth =~ /\A__/ } | |
@hidden_addributes = [:lock_version] | |
class << self; attr_accessor :hidden_attributes; end | |
# allows @presented_posts = Post.all.map(&PresenterProxy) | |
def self.to_proc | |
proc(&method(:new)) | |
end | |
def initialize(delegate_object) | |
@delegate = delegate_object | |
end | |
# FIXME: dependency on Hash#to_xml | |
def to_xml | |
@delegate.attributes.except(self.class.hidden_attributes).to_xml :root => obj.class.to_s | |
end | |
# FIXME: dependency on Hash#to_json | |
def to_json | |
@delegate.attributes.except(self.class.hidden_attributes).to_json | |
end | |
# TODO: more intelligent proxying | |
def method_missing(meth, *args, &block) | |
@delegate.send(meth, *args, &block) | |
end | |
def respond_to(method) | |
@delegate.respond_to?(method) || super | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment