Class: Renderer
- Inherits:
-
Object
- Object
- Renderer
- Defined in:
- lib/renderer.rb
Direct Known Subclasses
Instance Method Summary collapse
-
#initialize(default_path, layout) ⇒ Renderer
constructor
A new instance of Renderer.
-
#render(opt = nil, extra_options = {}) ⇒ Object
Teilweise aus rails…
Constructor Details
#initialize(default_path, layout) ⇒ Renderer
Returns a new instance of Renderer.
7 8 9 10 |
# File 'lib/renderer.rb', line 7 def initialize(default_path, layout) @_path = default_path @_layout = layout end |
Instance Method Details
#render(opt = nil, extra_options = {}) ⇒ Object
TODO:
better error-handling with partial and layout context information!!!
Teilweise aus rails…
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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/renderer.rb', line 14 def render(opt = nil, = {}) if opt.nil? opt = { :layout => @_layout } elsif opt.is_a?(String) || opt.is_a?(Symbol) [:template] = opt [:layout] ||= @_layout opt = elsif !opt.is_a?(Hash) [:partial] = opt opt = end if opt[:partial] # add underscore to last element of foo/bar/baz parts = opt[:partial].split('/') parts[-1] = "_"+parts.last begin template_file = File.read path_to_template(parts.join('/')) rescue Exception raise "Could not find Partial '#{opt[:partial]}'" end if opt[:collection] partial_name = opt[:partial].split('/').last opt[:collection].map { |item| define_singleton_method(partial_name) { item } ERB.new(template_file).result(binding) }.join "\n" else # If there are locals we have to save our instance binding, otherwise we will store our # newly created local-variables in the blockcontext of each_pair # values has to be defined explicitly to be overridden by the block and still available inside of eval if opt[:locals] value = nil instance_context = binding opt[:locals].each_pair do |local, value| Logger.warn("Please change your partial-name or local binding, because #{local} is already set in this context.") if respond_to? local define_singleton_method(local) { value } end end ERB.new(template_file).result(binding) end else # bind @current_path correctly to use in helpers and views if opt[:to_file] # Make absolute opt[:to_file] = File.(opt[:to_file], Configs.output) @current_path = File.dirname opt[:to_file] else @current_path ||= Configs.output end # render 'view_name', :option1 => 1, :option2 => 2 view = ERB.new(File.read path_to_template opt[:template]).result(binding) # then render with layout if opt[:layout] layout = File.read path_to_template opt[:layout] view = render_in_layout(layout) { view } end # Render to file, if desired if opt[:to_file] # create directories recursive FileUtils.mkpath File.dirname opt[:to_file] File.open(opt[:to_file], "w+") do |f| f.write view end else return view end end end |