public
Description: View delegate plugin for Rails
Homepage: http://stencil.rubyforge.org
Clone URL: git://github.com/bruce/stencil.git
stencil / lib / template_delegation.rb
100644 39 lines (30 sloc) 0.925 kb
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
module TemplateDelegation
  
  def self.included(base)
    base.send(:attr_accessor, :template)
    base.send(:delegate, :to_s, :to => :draw)
    base.send(:include, DelegationMethods)
    base.send(:include, OutputMethods)
  end
  
  module DelegationMethods
  
    def template_delegate(obj)
      returning obj do
        (class << obj; self; end).send(:include, TemplateDelegation)
        obj.template = self.template
        yield obj if block_given?
      end
    end
  
    # Forward all missing methods to +template+,
    # and write method directly to +template+ for future
    # invocations
    def method_missing(meth, *args, &block) #:nodoc:
      returning template.__send__(meth, *args, &block) do
        self.class.class_eval %{delegate :#{meth}, :to => :template}
      end
    end
    
  end
  
  module OutputMethods
    
    def erb(text, &b)
      ERB.new(text).result(binding)
    end
    
  end
  
end