ReinH (owner)

Revisions

  • 72b818 ReinH Wed Oct 07 12:46:41 -0700 2009
  • 8cbf80 ReinH Wed Oct 07 12:45:57 -0700 2009
  • 25e3d5 ReinH Wed Oct 07 12:45:09 -0700 2009
  • 0dee38 ReinH Wed Oct 07 12:43:12 -0700 2009
gist: 204366 Download_button fork
public
Public Clone URL: git://gist.github.com/204366.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 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