From eb9af20b7cc0e374277cf330bdd404f9daab28ec Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Thu, 22 Jan 2009 16:18:10 -0600 Subject: Begin unifying the interface between ActionController and ActionView --- actionpack/lib/action_view/base.rb | 91 +------ .../lib/action_view/helpers/prototype_helper.rb | 6 +- actionpack/lib/action_view/inline_template.rb | 19 -- actionpack/lib/action_view/partials.rb | 235 ---------------- actionpack/lib/action_view/paths.rb | 16 +- actionpack/lib/action_view/render/partials.rb | 300 +++++++++++++++++++++ actionpack/lib/action_view/render/rendering.rb | 119 ++++++++ actionpack/lib/action_view/renderable.rb | 96 ------- actionpack/lib/action_view/renderable_partial.rb | 47 ---- actionpack/lib/action_view/template.rb | 235 ---------------- actionpack/lib/action_view/template/error.rb | 99 +++++++ actionpack/lib/action_view/template/handler.rb | 34 +++ actionpack/lib/action_view/template/handlers.rb | 48 ++++ .../lib/action_view/template/handlers/builder.rb | 17 ++ .../lib/action_view/template/handlers/erb.rb | 22 ++ .../lib/action_view/template/handlers/rjs.rb | 13 + actionpack/lib/action_view/template/inline.rb | 19 ++ actionpack/lib/action_view/template/partial.rb | 18 ++ actionpack/lib/action_view/template/renderable.rb | 74 +++++ actionpack/lib/action_view/template/template.rb | 241 +++++++++++++++++ actionpack/lib/action_view/template_error.rb | 99 ------- actionpack/lib/action_view/template_handler.rb | 34 --- actionpack/lib/action_view/template_handlers.rb | 48 ---- .../lib/action_view/template_handlers/builder.rb | 17 -- .../lib/action_view/template_handlers/erb.rb | 22 -- .../lib/action_view/template_handlers/rjs.rb | 13 - actionpack/lib/action_view/test_case.rb | 19 +- 27 files changed, 1038 insertions(+), 963 deletions(-) delete mode 100644 actionpack/lib/action_view/inline_template.rb delete mode 100644 actionpack/lib/action_view/partials.rb create mode 100644 actionpack/lib/action_view/render/partials.rb create mode 100644 actionpack/lib/action_view/render/rendering.rb delete mode 100644 actionpack/lib/action_view/renderable.rb delete mode 100644 actionpack/lib/action_view/renderable_partial.rb delete mode 100644 actionpack/lib/action_view/template.rb create mode 100644 actionpack/lib/action_view/template/error.rb create mode 100644 actionpack/lib/action_view/template/handler.rb create mode 100644 actionpack/lib/action_view/template/handlers.rb create mode 100644 actionpack/lib/action_view/template/handlers/builder.rb create mode 100644 actionpack/lib/action_view/template/handlers/erb.rb create mode 100644 actionpack/lib/action_view/template/handlers/rjs.rb create mode 100644 actionpack/lib/action_view/template/inline.rb create mode 100644 actionpack/lib/action_view/template/partial.rb create mode 100644 actionpack/lib/action_view/template/renderable.rb create mode 100644 actionpack/lib/action_view/template/template.rb delete mode 100644 actionpack/lib/action_view/template_error.rb delete mode 100644 actionpack/lib/action_view/template_handler.rb delete mode 100644 actionpack/lib/action_view/template_handlers.rb delete mode 100644 actionpack/lib/action_view/template_handlers/builder.rb delete mode 100644 actionpack/lib/action_view/template_handlers/erb.rb delete mode 100644 actionpack/lib/action_view/template_handlers/rjs.rb (limited to 'actionpack/lib/action_view') diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 70a0ba91a7..80b8ea6a4c 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -160,14 +160,13 @@ module ActionView #:nodoc: # # See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details. class Base - include Helpers, Partials, ::ERB::Util + include Helpers, Rendering, Partials, ::ERB::Util + extend ActiveSupport::Memoizable - attr_accessor :base_path, :assigns, :template_extension + attr_accessor :base_path, :assigns, :template_extension, :formats attr_accessor :controller - attr_writer :template_format - attr_accessor :output_buffer class << self @@ -184,9 +183,13 @@ module ActionView #:nodoc: attr_internal :request + delegate :controller_path, :to => :controller, :allow_nil => true + delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers, :flash, :logger, :action_name, :controller_name, :to => :controller + delegate :find_by_parts, :to => :view_paths + module CompiledTemplates #:nodoc: # holds compiled template code end @@ -209,7 +212,8 @@ module ActionView #:nodoc: end end - def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil)#:nodoc: + def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil, formats = nil)#:nodoc: + @formats = formats || [:html] @assigns = assigns_for_first_render @assigns_added = nil @_render_stack = [] @@ -223,55 +227,7 @@ module ActionView #:nodoc: def view_paths=(paths) @view_paths = self.class.process_view_paths(paths) end - - # Returns the result of a render that's dictated by the options hash. The primary options are: - # - # * :partial - See ActionView::Partials. - # * :update - Calls update_page with the block given. - # * :file - Renders an explicit template file (this used to be the old default), add :locals to pass in those. - # * :inline - Renders an inline template similar to how it's done in the controller. - # * :text - Renders the text passed in out. - # - # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter - # as the locals hash. - def render(options = {}, local_assigns = {}, &block) #:nodoc: - local_assigns ||= {} - - case options - when Hash - options = options.reverse_merge(:locals => {}) - if options[:layout] - _render_with_layout(options, local_assigns, &block) - elsif options[:file] - tempalte = self.view_paths.find_template(options[:file], template_format) - tempalte.render_template(self, options[:locals]) - elsif options[:partial] - render_partial(options) - elsif options[:inline] - InlineTemplate.new(options[:inline], options[:type]).render(self, options[:locals]) - elsif options[:text] - options[:text] - end - when :update - update_page(&block) - else - render_partial(:partial => options, :locals => local_assigns) - end - end - - # The format to be used when choosing between multiple templates with - # the same name but differing formats. See +Request#template_format+ - # for more details. - def template_format - if defined? @template_format - @template_format - elsif controller && controller.respond_to?(:request) - @template_format = controller.request.template_format.to_sym - else - @template_format = :html - end - end - + # Access the current template being rendered. # Returns a ActionView::Template object. def template @@ -301,32 +257,5 @@ module ActionView #:nodoc: controller.response.content_type ||= content_type end end - - def _render_with_layout(options, local_assigns, &block) #:nodoc: - partial_layout = options.delete(:layout) - - if block_given? - begin - @_proc_for_layout = block - concat(render(options.merge(:partial => partial_layout))) - ensure - @_proc_for_layout = nil - end - else - begin - original_content_for_layout = @content_for_layout if defined?(@content_for_layout) - @content_for_layout = render(options) - - if (options[:inline] || options[:file] || options[:text]) - @cached_content_for_layout = @content_for_layout - render(:file => partial_layout, :locals => local_assigns) - else - render(options.merge(:partial => partial_layout)) - end - ensure - @content_for_layout = original_content_for_layout - end - end - end end end diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb index 18a209dcea..99676a9c27 100644 --- a/actionpack/lib/action_view/helpers/prototype_helper.rb +++ b/actionpack/lib/action_view/helpers/prototype_helper.rb @@ -987,13 +987,13 @@ module ActionView end def render(*options_for_render) - old_format = @context && @context.template_format - @context.template_format = :html if @context + old_formats = @context && @context.formats + @context.formats = [:html] if @context Hash === options_for_render.first ? @context.render(*options_for_render) : options_for_render.first.to_s ensure - @context.template_format = old_format if @context + @context.formats = old_formats if @context end def javascript_object_for(object) diff --git a/actionpack/lib/action_view/inline_template.rb b/actionpack/lib/action_view/inline_template.rb deleted file mode 100644 index 54efa543c8..0000000000 --- a/actionpack/lib/action_view/inline_template.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActionView #:nodoc: - class InlineTemplate #:nodoc: - include Renderable - - attr_reader :source, :extension, :method_segment - - def initialize(source, type = nil) - @source = source - @extension = type - @method_segment = "inline_#{@source.hash.abs}" - end - - private - # Always recompile inline templates - def recompile? - true - end - end -end diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb deleted file mode 100644 index 59e82b98a4..0000000000 --- a/actionpack/lib/action_view/partials.rb +++ /dev/null @@ -1,235 +0,0 @@ -module ActionView - # There's also a convenience method for rendering sub templates within the current controller that depends on a - # single object (we call this kind of sub templates for partials). It relies on the fact that partials should - # follow the naming convention of being prefixed with an underscore -- as to separate them from regular - # templates that could be rendered on their own. - # - # In a template for Advertiser#account: - # - # <%= render :partial => "account" %> - # - # This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable - # +account+ to the template for display. - # - # In another template for Advertiser#buy, we could have: - # - # <%= render :partial => "account", :locals => { :account => @buyer } %> - # - # <% for ad in @advertisements %> - # <%= render :partial => "ad", :locals => { :ad => ad } %> - # <% end %> - # - # This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then - # render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. - # - # == Rendering a collection of partials - # - # The example of partial use describes a familiar pattern where a template needs to iterate over an array and - # render a sub template for each of the elements. This pattern has been implemented as a single method that - # accepts an array and renders a partial by the same name as the elements contained within. So the three-lined - # example in "Using partials" can be rewritten with a single line: - # - # <%= render :partial => "ad", :collection => @advertisements %> - # - # This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An - # iteration counter will automatically be made available to the template with a name of the form - # +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+. - # - # NOTE: Due to backwards compatibility concerns, the collection can't be one of hashes. Normally you'd also - # just keep domain objects, like Active Records, in there. - # - # == Rendering shared partials - # - # Two controllers can share a set of partials and render them like this: - # - # <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %> - # - # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from. - # - # == Rendering objects with the RecordIdentifier - # - # Instead of explicitly naming the location of a partial, you can also let the RecordIdentifier do the work if - # you're following its conventions for RecordIdentifier#partial_path. Examples: - # - # # @account is an Account instance, so it uses the RecordIdentifier to replace - # # <%= render :partial => "accounts/account", :locals => { :account => @buyer } %> - # <%= render :partial => @account %> - # - # # @posts is an array of Post instances, so it uses the RecordIdentifier to replace - # # <%= render :partial => "posts/post", :collection => @posts %> - # <%= render :partial => @posts %> - # - # == Rendering the default case - # - # If you're not going to be using any of the options like collections or layouts, you can also use the short-hand - # defaults of render to render partials. Examples: - # - # # Instead of <%= render :partial => "account" %> - # <%= render "account" %> - # - # # Instead of <%= render :partial => "account", :locals => { :account => @buyer } %> - # <%= render "account", :account => @buyer %> - # - # # @account is an Account instance, so it uses the RecordIdentifier to replace - # # <%= render :partial => "accounts/account", :locals => { :account => @account } %> - # <%= render(@account) %> - # - # # @posts is an array of Post instances, so it uses the RecordIdentifier to replace - # # <%= render :partial => "posts/post", :collection => @posts %> - # <%= render(@posts) %> - # - # == Rendering partials with layouts - # - # Partials can have their own layouts applied to them. These layouts are different than the ones that are - # specified globally for the entire action, but they work in a similar fashion. Imagine a list with two types - # of users: - # - # <%# app/views/users/index.html.erb &> - # Here's the administrator: - # <%= render :partial => "user", :layout => "administrator", :locals => { :user => administrator } %> - # - # Here's the editor: - # <%= render :partial => "user", :layout => "editor", :locals => { :user => editor } %> - # - # <%# app/views/users/_user.html.erb &> - # Name: <%= user.name %> - # - # <%# app/views/users/_administrator.html.erb &> - #
- # Budget: $<%= user.budget %> - # <%= yield %> - #
- # - # <%# app/views/users/_editor.html.erb &> - #
- # Deadline: <%= user.deadline %> - # <%= yield %> - #
- # - # ...this will return: - # - # Here's the administrator: - #
- # Budget: $<%= user.budget %> - # Name: <%= user.name %> - #
- # - # Here's the editor: - #
- # Deadline: <%= user.deadline %> - # Name: <%= user.name %> - #
- # - # You can also apply a layout to a block within any template: - # - # <%# app/views/users/_chief.html.erb &> - # <% render(:layout => "administrator", :locals => { :user => chief }) do %> - # Title: <%= chief.title %> - # <% end %> - # - # ...this will return: - # - #
- # Budget: $<%= user.budget %> - # Title: <%= chief.name %> - #
- # - # As you can see, the :locals hash is shared between both the partial and its layout. - # - # If you pass arguments to "yield" then this will be passed to the block. One way to use this is to pass - # an array to layout and treat it as an enumerable. - # - # <%# app/views/users/_user.html.erb &> - #
- # Budget: $<%= user.budget %> - # <%= yield user %> - #
- # - # <%# app/views/users/index.html.erb &> - # <% render :layout => @users do |user| %> - # Title: <%= user.title %> - # <% end %> - # - # This will render the layout for each user and yield to the block, passing the user, each time. - # - # You can also yield multiple times in one layout and use block arguments to differentiate the sections. - # - # <%# app/views/users/_user.html.erb &> - #
- # <%= yield user, :header %> - # Budget: $<%= user.budget %> - # <%= yield user, :footer %> - #
- # - # <%# app/views/users/index.html.erb &> - # <% render :layout => @users do |user, section| %> - # <%- case section when :header -%> - # Title: <%= user.title %> - # <%- when :footer -%> - # Deadline: <%= user.deadline %> - # <%- end -%> - # <% end %> - module Partials - extend ActiveSupport::Memoizable - - private - def render_partial(options = {}) #:nodoc: - local_assigns = options[:locals] || {} - - case partial_path = options[:partial] - when String, Symbol, NilClass - if options.has_key?(:collection) - render_partial_collection(options) - else - _pick_partial_template(partial_path).render_partial(self, options[:object], local_assigns) - end - when ActionView::Helpers::FormBuilder - builder_partial_path = partial_path.class.to_s.demodulize.underscore.sub(/_builder$/, '') - local_assigns.merge!(builder_partial_path.to_sym => partial_path) - render_partial(:partial => builder_partial_path, :object => options[:object], :locals => local_assigns) - when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope - render_partial_collection(options.except(:partial).merge(:collection => partial_path)) - else - object = partial_path - render_partial( - :partial => ActionController::RecordIdentifier.partial_path(object, controller.class.controller_path), - :object => object, - :locals => local_assigns - ) - end - end - - def render_partial_collection(options = {}) #:nodoc: - return nil if options[:collection].blank? - - partial = options[:partial] - spacer = options[:spacer_template] ? render(:partial => options[:spacer_template]) : '' - local_assigns = options[:locals] ? options[:locals].clone : {} - as = options[:as] - - index = 0 - options[:collection].map do |object| - _partial_path ||= partial || - ActionController::RecordIdentifier.partial_path(object, controller.class.controller_path) - template = _pick_partial_template(_partial_path) - local_assigns[template.counter_name] = index - result = template.render_partial(self, object, local_assigns.dup, as) - index += 1 - result - end.join(spacer) - end - - def _pick_partial_template(partial_path) #:nodoc: - if partial_path.include?('/') - path = File.join(File.dirname(partial_path), "_#{File.basename(partial_path)}") - elsif controller - path = "#{controller.class.controller_path}/_#{partial_path}" - else - path = "_#{partial_path}" - end - - self.view_paths.find_template(path, self.template_format) - end - memoize :_pick_partial_template - end -end diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/paths.rb index 19207e7262..4c3a226ac6 100644 --- a/actionpack/lib/action_view/paths.rb +++ b/actionpack/lib/action_view/paths.rb @@ -32,14 +32,24 @@ module ActionView #:nodoc: super(*objs.map { |obj| self.class.type_cast(obj) }) end + def find_by_parts(path, extension = nil, prefix = nil, partial = false) + template_path = path.sub(/^\//, '') + + each do |load_path| + if template = load_path.find_by_parts(template_path, extension, prefix, partial) + return template + end + end + + Template.new(path, self) + end + def find_template(original_template_path, format = nil) return original_template_path if original_template_path.respond_to?(:render) template_path = original_template_path.sub(/^\//, '') each do |load_path| - if format && (template = load_path["#{template_path}.#{format}"]) - return template - elsif template = load_path[template_path] + if template = load_path.find_by_parts(template_path, format) return template end end diff --git a/actionpack/lib/action_view/render/partials.rb b/actionpack/lib/action_view/render/partials.rb new file mode 100644 index 0000000000..aa4c4af213 --- /dev/null +++ b/actionpack/lib/action_view/render/partials.rb @@ -0,0 +1,300 @@ +module ActionView + # There's also a convenience method for rendering sub templates within the current controller that depends on a + # single object (we call this kind of sub templates for partials). It relies on the fact that partials should + # follow the naming convention of being prefixed with an underscore -- as to separate them from regular + # templates that could be rendered on their own. + # + # In a template for Advertiser#account: + # + # <%= render :partial => "account" %> + # + # This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable + # +account+ to the template for display. + # + # In another template for Advertiser#buy, we could have: + # + # <%= render :partial => "account", :locals => { :account => @buyer } %> + # + # <% for ad in @advertisements %> + # <%= render :partial => "ad", :locals => { :ad => ad } %> + # <% end %> + # + # This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then + # render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. + # + # == Rendering a collection of partials + # + # The example of partial use describes a familiar pattern where a template needs to iterate over an array and + # render a sub template for each of the elements. This pattern has been implemented as a single method that + # accepts an array and renders a partial by the same name as the elements contained within. So the three-lined + # example in "Using partials" can be rewritten with a single line: + # + # <%= render :partial => "ad", :collection => @advertisements %> + # + # This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An + # iteration counter will automatically be made available to the template with a name of the form + # +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+. + # + # NOTE: Due to backwards compatibility concerns, the collection can't be one of hashes. Normally you'd also + # just keep domain objects, like Active Records, in there. + # + # == Rendering shared partials + # + # Two controllers can share a set of partials and render them like this: + # + # <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %> + # + # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from. + # + # == Rendering objects with the RecordIdentifier + # + # Instead of explicitly naming the location of a partial, you can also let the RecordIdentifier do the work if + # you're following its conventions for RecordIdentifier#partial_path. Examples: + # + # # @account is an Account instance, so it uses the RecordIdentifier to replace + # # <%= render :partial => "accounts/account", :locals => { :account => @buyer } %> + # <%= render :partial => @account %> + # + # # @posts is an array of Post instances, so it uses the RecordIdentifier to replace + # # <%= render :partial => "posts/post", :collection => @posts %> + # <%= render :partial => @posts %> + # + # == Rendering the default case + # + # If you're not going to be using any of the options like collections or layouts, you can also use the short-hand + # defaults of render to render partials. Examples: + # + # # Instead of <%= render :partial => "account" %> + # <%= render "account" %> + # + # # Instead of <%= render :partial => "account", :locals => { :account => @buyer } %> + # <%= render "account", :account => @buyer %> + # + # # @account is an Account instance, so it uses the RecordIdentifier to replace + # # <%= render :partial => "accounts/account", :locals => { :account => @account } %> + # <%= render(@account) %> + # + # # @posts is an array of Post instances, so it uses the RecordIdentifier to replace + # # <%= render :partial => "posts/post", :collection => @posts %> + # <%= render(@posts) %> + # + # == Rendering partials with layouts + # + # Partials can have their own layouts applied to them. These layouts are different than the ones that are + # specified globally for the entire action, but they work in a similar fashion. Imagine a list with two types + # of users: + # + # <%# app/views/users/index.html.erb &> + # Here's the administrator: + # <%= render :partial => "user", :layout => "administrator", :locals => { :user => administrator } %> + # + # Here's the editor: + # <%= render :partial => "user", :layout => "editor", :locals => { :user => editor } %> + # + # <%# app/views/users/_user.html.erb &> + # Name: <%= user.name %> + # + # <%# app/views/users/_administrator.html.erb &> + #
+ # Budget: $<%= user.budget %> + # <%= yield %> + #
+ # + # <%# app/views/users/_editor.html.erb &> + #
+ # Deadline: <%= user.deadline %> + # <%= yield %> + #
+ # + # ...this will return: + # + # Here's the administrator: + #
+ # Budget: $<%= user.budget %> + # Name: <%= user.name %> + #
+ # + # Here's the editor: + #
+ # Deadline: <%= user.deadline %> + # Name: <%= user.name %> + #
+ # + # You can also apply a layout to a block within any template: + # + # <%# app/views/users/_chief.html.erb &> + # <% render(:layout => "administrator", :locals => { :user => chief }) do %> + # Title: <%= chief.title %> + # <% end %> + # + # ...this will return: + # + #
+ # Budget: $<%= user.budget %> + # Title: <%= chief.name %> + #
+ # + # As you can see, the :locals hash is shared between both the partial and its layout. + # + # If you pass arguments to "yield" then this will be passed to the block. One way to use this is to pass + # an array to layout and treat it as an enumerable. + # + # <%# app/views/users/_user.html.erb &> + #
+ # Budget: $<%= user.budget %> + # <%= yield user %> + #
+ # + # <%# app/views/users/index.html.erb &> + # <% render :layout => @users do |user| %> + # Title: <%= user.title %> + # <% end %> + # + # This will render the layout for each user and yield to the block, passing the user, each time. + # + # You can also yield multiple times in one layout and use block arguments to differentiate the sections. + # + # <%# app/views/users/_user.html.erb &> + #
+ # <%= yield user, :header %> + # Budget: $<%= user.budget %> + # <%= yield user, :footer %> + #
+ # + # <%# app/views/users/index.html.erb &> + # <% render :layout => @users do |user, section| %> + # <%- case section when :header -%> + # Title: <%= user.title %> + # <%- when :footer -%> + # Deadline: <%= user.deadline %> + # <%- end -%> + # <% end %> + module Partials + extend ActiveSupport::Memoizable + + def _render_partial(options = {}) #:nodoc: + options[:locals] ||= {} + + case path = partial = options[:partial] + when *_array_like_objects + return _render_partial_collection(partial, options) + else + if partial.is_a?(ActionView::Helpers::FormBuilder) + path = partial.class.to_s.demodulize.underscore.sub(/_builder$/, '') + options[:locals].merge!(path.to_sym => partial) + elsif !partial.is_a?(String) + options[:object] = object = partial + path = ActionController::RecordIdentifier.partial_path(object, controller_path) + end + _, _, prefix, object = parts = partial_parts(path, options) + template = find_by_parts(*parts) + _render_partial_object(template, options, (object unless object == true)) + end + end + + private + def partial_parts(name, options) + segments = name.split("/") + parts = segments.pop.split(".") + + case parts.size + when 1 + parts + when 2, 3 + extension = parts.delete_at(1).to_sym + if formats.include?(extension) + self.formats.replace [extension] + end + parts.pop if parts.size == 2 + end + + path = parts.join(".") + prefix = segments[0..-1].join("/") + prefix = prefix.blank? ? controller_path : prefix + parts = [path, formats, prefix] + parts.push options[:object] || true + end + + def _render_partial_with_block(layout, block, options) + @_proc_for_layout = block + concat(_render_partial(options.merge(:partial => layout))) + ensure + @_proc_for_layout = nil + end + + def _render_partial_with_layout(layout, options) + if layout + prefix = controller && !layout.include?("/") ? controller.controller_path : nil + layout = find_by_parts(layout, formats, prefix, true) + end + content = _render_partial(options) + return _render_content_with_layout(content, layout, options[:locals]) + end + + def _deprecated_ivar_assign(template) + if respond_to?(:controller) + ivar = :"@#{template.variable_name}" + object = + if controller.instance_variable_defined?(ivar) + ActiveSupport::Deprecation::DeprecatedObjectProxy.new( + controller.instance_variable_get(ivar), + "#{ivar} will no longer be implicitly assigned to #{template.variable_name}") + end + end + end + + def _array_like_objects + array_like = [Array] + if defined?(ActiveRecord) + array_like.push(ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope) + end + array_like + end + + def _render_partial_object(template, options, object = nil) + if options.key?(:collection) + _render_partial_collection(options.delete(:collection), options, template) + else + locals = (options[:locals] ||= {}) + object ||= locals[:object] || locals[template.variable_name] + + _set_locals(object, locals, template, options) + _render_template(template, locals) + end + end + + def _set_locals(object, locals, template, options) + object ||= _deprecated_ivar_assign(template) + locals[:object] = locals[template.variable_name] = object + locals[options[:as]] = object if options[:as] + end + + def _render_partial_collection(collection, options = {}, passed_template = nil) #:nodoc: + return nil if collection.blank? + + spacer = options[:spacer_template] ? _render_partial(:partial => options[:spacer_template]) : '' + + locals = (options[:locals] ||= {}) + index, @_partial_path = 0, nil + collection.map do |object| + template = passed_template || begin + _partial_path = + ActionController::RecordIdentifier.partial_path(object, controller_path) + template = _pick_partial_template(_partial_path) + end + + _set_locals(object, locals, template, options) + locals[template.counter_name] = index + + index += 1 + _render_template(template, locals) + end.join(spacer) + end + + def _pick_partial_template(partial_path) #:nodoc: + prefix = controller_path unless partial_path.include?('/') + find_by_parts(partial_path, formats, prefix, true) + end + memoize :_pick_partial_template + end +end diff --git a/actionpack/lib/action_view/render/rendering.rb b/actionpack/lib/action_view/render/rendering.rb new file mode 100644 index 0000000000..a02c058725 --- /dev/null +++ b/actionpack/lib/action_view/render/rendering.rb @@ -0,0 +1,119 @@ +module ActionView + module Rendering + # Returns the result of a render that's dictated by the options hash. The primary options are: + # + # * :partial - See ActionView::Partials. + # * :update - Calls update_page with the block given. + # * :file - Renders an explicit template file (this used to be the old default), add :locals to pass in those. + # * :inline - Renders an inline template similar to how it's done in the controller. + # * :text - Renders the text passed in out. + # + # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter + # as the locals hash. + def render(options = {}, local_assigns = {}, &block) #:nodoc: + local_assigns ||= {} + + @exempt_from_layout = true + + case options + when Hash + options[:locals] ||= {} + layout = options[:layout] + + return _render_partial_with_layout(layout, options) if options.key?(:partial) + return _render_partial_with_block(layout, block, options) if block_given? + + layout = find_by_parts(layout, formats) if layout + + if file = options[:file] + template = find_by_parts(file, formats) + _render_template_with_layout(template, layout, :locals => options[:locals]) + elsif inline = options[:inline] + _render_inline(inline, layout, options) + elsif text = options[:text] + _render_text(text, layout, options) + end + when :update + update_page(&block) + when String, NilClass + _render_partial(:partial => options, :locals => local_assigns) + end + end + + def _render_content_with_layout(content, layout, locals) + return content unless layout + + locals ||= {} + + if controller && layout + response.layout = layout.path_without_format_and_extension if controller.respond_to?(:response) + logger.info("Rendering template within #{layout.path_without_format_and_extension}") if logger + end + + begin + original_content_for_layout = @content_for_layout if defined?(@content_for_layout) + @content_for_layout = content + + @cached_content_for_layout = @content_for_layout + _render_template(layout, locals) + ensure + @content_for_layout = original_content_for_layout + end + end + + def _render_template(template, local_assigns = {}) + template.compile(local_assigns) + + @_render_stack.push(template) + + _evaluate_assigns_and_ivars + _set_controller_content_type(template.mime_type) if template.respond_to?(:mime_type) + + result = send(template.method_name(local_assigns), local_assigns) do |*names| + if !instance_variable_defined?(:"@content_for_#{names.first}") && + instance_variable_defined?(:@_proc_for_layout) && (proc = @_proc_for_layout) + capture(*names, &proc) + elsif instance_variable_defined?(ivar = :"@content_for_#{names.first || :layout}") + instance_variable_get(ivar) + end + end + + @_render_stack.pop + result + rescue Exception => e + raise e if !template.filename || template.is_a?(InlineTemplate) + if TemplateError === e + e.sub_template_of(template) + raise e + else + raise TemplateError.new(template, assigns, e) + end + end + + def _render_inline(inline, layout, options) + content = _render_template(InlineTemplate.new(options[:inline], options[:type]), options[:locals] || {}) + layout ? _render_content_with_layout(content, layout, options[:locals]) : content + end + + def _render_text(text, layout, options) + layout ? _render_content_with_layout(text, layout, options[:locals]) : text + end + + def _render_template_with_layout(template, layout = nil, options = {}, partial = false) + if controller && logger + logger.info("Rendering #{template.path_without_extension}" + + (options[:status] ? " (#{options[:status]})" : '')) + end + + content = if partial + object = partial unless partial == true + _render_partial_object(template, options, object) + else + _render_template(template, options[:locals] || {}) + end + + return content unless layout && !template.exempt_from_layout? + _render_content_with_layout(content, layout, options[:locals] || {}) + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_view/renderable.rb b/actionpack/lib/action_view/renderable.rb deleted file mode 100644 index 153e14f68b..0000000000 --- a/actionpack/lib/action_view/renderable.rb +++ /dev/null @@ -1,96 +0,0 @@ -module ActionView - # NOTE: The template that this mixin is being included into is frozen - # so you cannot set or modify any instance variables - module Renderable #:nodoc: - extend ActiveSupport::Memoizable - - def filename - 'compiled-template' - end - - def handler - Template.handler_class_for_extension(extension) - end - memoize :handler - - def compiled_source - handler.call(self) - end - memoize :compiled_source - - def method_name_without_locals - ['_run', extension, method_segment].compact.join('_') - end - memoize :method_name_without_locals - - def render(view, local_assigns = {}) - compile(local_assigns) - - stack = view.instance_variable_get(:@_render_stack) - stack.push(self) - - view.send(:_evaluate_assigns_and_ivars) - view.send(:_set_controller_content_type, mime_type) if respond_to?(:mime_type) - - result = view.send(method_name(local_assigns), local_assigns) do |*names| - ivar = :@_proc_for_layout - if !view.instance_variable_defined?(:"@content_for_#{names.first}") && view.instance_variable_defined?(ivar) && (proc = view.instance_variable_get(ivar)) - view.capture(*names, &proc) - elsif view.instance_variable_defined?(ivar = :"@content_for_#{names.first || :layout}") - view.instance_variable_get(ivar) - end - end - - stack.pop - result - end - - def method_name(local_assigns) - if local_assigns && local_assigns.any? - method_name = method_name_without_locals.dup - method_name << "_locals_#{local_assigns.keys.map { |k| k.to_s }.sort.join('_')}" - else - method_name = method_name_without_locals - end - method_name.to_sym - end - - private - # Compile and evaluate the template's code (if necessary) - def compile(local_assigns) - render_symbol = method_name(local_assigns) - - if !Base::CompiledTemplates.method_defined?(render_symbol) || recompile? - compile!(render_symbol, local_assigns) - end - end - - def compile!(render_symbol, local_assigns) - locals_code = local_assigns.keys.map { |key| "#{key} = local_assigns[:#{key}];" }.join - - source = <<-end_src - def #{render_symbol}(local_assigns) - old_output_buffer = output_buffer;#{locals_code};#{compiled_source} - ensure - self.output_buffer = old_output_buffer - end - end_src - - begin - ActionView::Base::CompiledTemplates.module_eval(source, filename, 0) - rescue Exception => e # errors from template code - if logger = defined?(ActionController) && Base.logger - logger.debug "ERROR: compiling #{render_symbol} RAISED #{e}" - logger.debug "Function body: #{source}" - logger.debug "Backtrace: #{e.backtrace.join("\n")}" - end - - raise ActionView::TemplateError.new(self, {}, e) - end - end - - def recompile? - false - end - end -end diff --git a/actionpack/lib/action_view/renderable_partial.rb b/actionpack/lib/action_view/renderable_partial.rb deleted file mode 100644 index 3ea836fa25..0000000000 --- a/actionpack/lib/action_view/renderable_partial.rb +++ /dev/null @@ -1,47 +0,0 @@ -module ActionView - # NOTE: The template that this mixin is being included into is frozen - # so you cannot set or modify any instance variables - module RenderablePartial #:nodoc: - extend ActiveSupport::Memoizable - - def variable_name - name.sub(/\A_/, '').to_sym - end - memoize :variable_name - - def counter_name - "#{variable_name}_counter".to_sym - end - memoize :counter_name - - def render(view, local_assigns = {}) - if defined? ActionController - ActionController::Base.benchmark("Rendered #{path_without_format_and_extension}", Logger::DEBUG, false) do - super - end - else - super - end - end - - def render_partial(view, object = nil, local_assigns = {}, as = nil) - object ||= local_assigns[:object] || local_assigns[variable_name] - - if object.nil? && view.respond_to?(:controller) - ivar = :"@#{variable_name}" - object = - if view.controller.instance_variable_defined?(ivar) - ActiveSupport::Deprecation::DeprecatedObjectProxy.new( - view.controller.instance_variable_get(ivar), - "#{ivar} will no longer be implicitly assigned to #{variable_name}") - end - end - - # Ensure correct object is reassigned to other accessors - local_assigns[:object] = local_assigns[variable_name] = object - local_assigns[as] = object if as - - render_template(view, local_assigns) - end - end -end diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb deleted file mode 100644 index 9d1e0d3ac5..0000000000 --- a/actionpack/lib/action_view/template.rb +++ /dev/null @@ -1,235 +0,0 @@ -module ActionView #:nodoc: - class Template - class Path - attr_reader :path, :paths - delegate :hash, :inspect, :to => :path - - def initialize(path) - raise ArgumentError, "path already is a Path class" if path.is_a?(Path) - @path = path.freeze - end - - def to_s - if defined?(RAILS_ROOT) - path.to_s.sub(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') - else - path.to_s - end - end - - def to_str - path.to_str - end - - def ==(path) - to_str == path.to_str - end - - def eql?(path) - to_str == path.to_str - end - - # Returns a ActionView::Template object for the given path string. The - # input path should be relative to the view path directory, - # +hello/index.html.erb+. This method also has a special exception to - # match partial file names without a handler extension. So - # +hello/index.html+ will match the first template it finds with a - # known template extension, +hello/index.html.erb+. Template extensions - # should not be confused with format extensions +html+, +js+, +xml+, - # etc. A format must be supplied to match a formated file. +hello/index+ - # will never match +hello/index.html.erb+. - def [](path) - templates_in_path do |template| - if template.accessible_paths.include?(path) - return template - end - end - nil - end - - private - def templates_in_path - (Dir.glob("#{@path}/**/*/**") | Dir.glob("#{@path}/**")).each do |file| - yield create_template(file) unless File.directory?(file) - end - end - - def create_template(file) - Template.new(file.split("#{self}/").last, self) - end - end - - class EagerPath < Path - def initialize(path) - super - - @paths = {} - templates_in_path do |template| - template.load! - template.accessible_paths.each do |path| - @paths[path] = template - end - end - @paths.freeze - end - - def [](path) - @paths[path] - end - end - - extend TemplateHandlers - extend ActiveSupport::Memoizable - include Renderable - - # Templates that are exempt from layouts - @@exempt_from_layout = Set.new([/\.rjs$/]) - - # Don't render layouts for templates with the given extensions. - def self.exempt_from_layout(*extensions) - regexps = extensions.collect do |extension| - extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/ - end - @@exempt_from_layout.merge(regexps) - end - - attr_accessor :filename, :load_path, :base_path, :name, :format, :extension - delegate :to_s, :to => :path - - def initialize(template_path, load_paths = []) - template_path = template_path.dup - @load_path, @filename = find_full_path(template_path, load_paths) - @base_path, @name, @format, @extension = split(template_path) - @base_path.to_s.gsub!(/\/$/, '') # Push to split method - - # Extend with partial super powers - extend RenderablePartial if @name =~ /^_/ - end - - def accessible_paths - paths = [] - paths << path - paths << path_without_extension - if multipart? - formats = format.split(".") - paths << "#{path_without_format_and_extension}.#{formats.first}" - paths << "#{path_without_format_and_extension}.#{formats.second}" - end - paths - end - - def format_and_extension - (extensions = [format, extension].compact.join(".")).blank? ? nil : extensions - end - memoize :format_and_extension - - def multipart? - format && format.include?('.') - end - - def content_type - format.gsub('.', '/') - end - - def mime_type - Mime::Type.lookup_by_extension(format) if format - end - memoize :mime_type - - def path - [base_path, [name, format, extension].compact.join('.')].compact.join('/') - end - memoize :path - - def path_without_extension - [base_path, [name, format].compact.join('.')].compact.join('/') - end - memoize :path_without_extension - - def path_without_format_and_extension - [base_path, name].compact.join('/') - end - memoize :path_without_format_and_extension - - def relative_path - path = File.expand_path(filename) - path.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') if defined?(RAILS_ROOT) - path - end - memoize :relative_path - - def exempt_from_layout? - @@exempt_from_layout.any? { |exempted| path =~ exempted } - end - - def mtime - File.mtime(filename) - end - memoize :mtime - - def source - File.read(filename) - end - memoize :source - - def method_segment - relative_path.to_s.gsub(/([^a-zA-Z0-9_])/) { $1.ord } - end - memoize :method_segment - - def render_template(view, local_assigns = {}) - render(view, local_assigns) - rescue Exception => e - raise e unless filename - if TemplateError === e - e.sub_template_of(self) - raise e - else - raise TemplateError.new(self, view.assigns, e) - end - end - - def stale? - File.mtime(filename) > mtime - end - - def recompile? - !@cached - end - - def load! - @cached = true - freeze - end - - private - def valid_extension?(extension) - !Template.registered_template_handler(extension).nil? - end - - def find_full_path(path, load_paths) - load_paths = Array(load_paths) + [nil] - load_paths.each do |load_path| - file = load_path ? "#{load_path.to_str}/#{path}" : path - return load_path, file if File.file?(file) - end - raise MissingTemplate.new(load_paths, path) - end - - # Returns file split into an array - # [base_path, name, format, extension] - def split(file) - if m = file.match(/^(.*\/)?([^\.]+)\.?(\w+)?\.?(\w+)?\.?(\w+)?$/) - if valid_extension?(m[5]) # Multipart formats - [m[1], m[2], "#{m[3]}.#{m[4]}", m[5]] - elsif valid_extension?(m[4]) # Single format - [m[1], m[2], m[3], m[4]] - elsif valid_extension?(m[3]) # No format - [m[1], m[2], nil, m[3]] - else # No extension - [m[1], m[2], m[3], nil] - end - end - end - end -end diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb new file mode 100644 index 0000000000..37cb1c7c6c --- /dev/null +++ b/actionpack/lib/action_view/template/error.rb @@ -0,0 +1,99 @@ +module ActionView + # The TemplateError exception is raised when the compilation of the template fails. This exception then gathers a + # bunch of intimate details and uses it to report a very precise exception message. + class TemplateError < ActionViewError #:nodoc: + SOURCE_CODE_RADIUS = 3 + + attr_reader :original_exception + + def initialize(template, assigns, original_exception) + @template, @assigns, @original_exception = template, assigns.dup, original_exception + @backtrace = compute_backtrace + end + + def file_name + @template.relative_path + end + + def message + ActiveSupport::Deprecation.silence { original_exception.message } + end + + def clean_backtrace + if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner) + Rails.backtrace_cleaner.clean(original_exception.backtrace) + else + original_exception.backtrace + end + end + + def sub_template_message + if @sub_templates + "Trace of template inclusion: " + + @sub_templates.collect { |template| template.relative_path }.join(", ") + else + "" + end + end + + def source_extract(indentation = 0) + return unless num = line_number + num = num.to_i + + source_code = @template.source.split("\n") + + start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max + end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min + + indent = ' ' * indentation + line_counter = start_on_line + return unless source_code = source_code[start_on_line..end_on_line] + + source_code.sum do |line| + line_counter += 1 + "#{indent}#{line_counter}: #{line}\n" + end + end + + def sub_template_of(template_path) + @sub_templates ||= [] + @sub_templates << template_path + end + + def line_number + @line_number ||= + if file_name + regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/ + + $1 if message =~ regexp or clean_backtrace.find { |line| line =~ regexp } + end + end + + def to_s + "\n#{self.class} (#{message}) #{source_location}:\n" + + "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n" + end + + # don't do anything nontrivial here. Any raised exception from here becomes fatal + # (and can't be rescued). + def backtrace + @backtrace + end + + private + def compute_backtrace + [ + "#{source_location.capitalize}\n\n#{source_extract(4)}\n " + + clean_backtrace.join("\n ") + ] + end + + def source_location + if line_number + "on line ##{line_number} of " + else + 'in ' + end + file_name + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_view/template/handler.rb b/actionpack/lib/action_view/template/handler.rb new file mode 100644 index 0000000000..672da0ed2b --- /dev/null +++ b/actionpack/lib/action_view/template/handler.rb @@ -0,0 +1,34 @@ +# Legacy TemplateHandler stub +module ActionView + module TemplateHandlers #:nodoc: + module Compilable + def self.included(base) + base.extend(ClassMethods) + end + + module ClassMethods + def call(template) + new.compile(template) + end + end + + def compile(template) + raise "Need to implement #{self.class.name}#compile(template)" + end + end + end + + class TemplateHandler + def self.call(template) + "#{name}.new(self).render(template, local_assigns)" + end + + def initialize(view = nil) + @view = view + end + + def render(template, local_assigns) + raise "Need to implement #{self.class.name}#render(template, local_assigns)" + end + end +end diff --git a/actionpack/lib/action_view/template/handlers.rb b/actionpack/lib/action_view/template/handlers.rb new file mode 100644 index 0000000000..fb85f28851 --- /dev/null +++ b/actionpack/lib/action_view/template/handlers.rb @@ -0,0 +1,48 @@ +module ActionView #:nodoc: + module TemplateHandlers #:nodoc: + autoload :ERB, 'action_view/template/handlers/erb' + autoload :RJS, 'action_view/template/handlers/rjs' + autoload :Builder, 'action_view/template/handlers/builder' + + def self.extended(base) + base.register_default_template_handler :erb, TemplateHandlers::ERB + base.register_template_handler :rjs, TemplateHandlers::RJS + base.register_template_handler :builder, TemplateHandlers::Builder + + # TODO: Depreciate old template extensions + base.register_template_handler :rhtml, TemplateHandlers::ERB + base.register_template_handler :rxml, TemplateHandlers::Builder + end + + @@template_handlers = {} + @@default_template_handlers = nil + + # Register a class that knows how to handle template files with the given + # extension. This can be used to implement new template types. + # The constructor for the class must take the ActiveView::Base instance + # as a parameter, and the class must implement a +render+ method that + # takes the contents of the template to render as well as the Hash of + # local assigns available to the template. The +render+ method ought to + # return the rendered template as a string. + def register_template_handler(extension, klass) + @@template_handlers[extension.to_sym] = klass + end + + def template_handler_extensions + @@template_handlers.keys.map(&:to_s).sort + end + + def registered_template_handler(extension) + extension && @@template_handlers[extension.to_sym] + end + + def register_default_template_handler(extension, klass) + register_template_handler(extension, klass) + @@default_template_handlers = klass + end + + def handler_class_for_extension(extension) + registered_template_handler(extension) || @@default_template_handlers + end + end +end diff --git a/actionpack/lib/action_view/template/handlers/builder.rb b/actionpack/lib/action_view/template/handlers/builder.rb new file mode 100644 index 0000000000..788dc93326 --- /dev/null +++ b/actionpack/lib/action_view/template/handlers/builder.rb @@ -0,0 +1,17 @@ +require 'builder' + +module ActionView + module TemplateHandlers + class Builder < TemplateHandler + include Compilable + + def compile(template) + "_set_controller_content_type(Mime::XML);" + + "xml = ::Builder::XmlMarkup.new(:indent => 2);" + + "self.output_buffer = xml.target!;" + + template.source + + ";xml.target!;" + end + end + end +end diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb new file mode 100644 index 0000000000..e3120ba267 --- /dev/null +++ b/actionpack/lib/action_view/template/handlers/erb.rb @@ -0,0 +1,22 @@ +module ActionView + module TemplateHandlers + class ERB < TemplateHandler + include Compilable + + ## + # :singleton-method: + # Specify trim mode for the ERB compiler. Defaults to '-'. + # See ERb documentation for suitable values. + cattr_accessor :erb_trim_mode + self.erb_trim_mode = '-' + + def compile(template) + src = ::ERB.new("<% __in_erb_template=true %>#{template.source}", nil, erb_trim_mode, '@output_buffer').src + + # Ruby 1.9 prepends an encoding to the source. However this is + # useless because you can only set an encoding on the first line + RUBY_VERSION >= '1.9' ? src.sub(/\A#coding:.*\n/, '') : src + end + end + end +end diff --git a/actionpack/lib/action_view/template/handlers/rjs.rb b/actionpack/lib/action_view/template/handlers/rjs.rb new file mode 100644 index 0000000000..802a79b3fc --- /dev/null +++ b/actionpack/lib/action_view/template/handlers/rjs.rb @@ -0,0 +1,13 @@ +module ActionView + module TemplateHandlers + class RJS < TemplateHandler + include Compilable + + def compile(template) + "@formats = [:html];" + + "controller.response.content_type ||= Mime::JS;" + + "update_page do |page|;#{template.source}\nend" + end + end + end +end diff --git a/actionpack/lib/action_view/template/inline.rb b/actionpack/lib/action_view/template/inline.rb new file mode 100644 index 0000000000..54efa543c8 --- /dev/null +++ b/actionpack/lib/action_view/template/inline.rb @@ -0,0 +1,19 @@ +module ActionView #:nodoc: + class InlineTemplate #:nodoc: + include Renderable + + attr_reader :source, :extension, :method_segment + + def initialize(source, type = nil) + @source = source + @extension = type + @method_segment = "inline_#{@source.hash.abs}" + end + + private + # Always recompile inline templates + def recompile? + true + end + end +end diff --git a/actionpack/lib/action_view/template/partial.rb b/actionpack/lib/action_view/template/partial.rb new file mode 100644 index 0000000000..30dec1dc5b --- /dev/null +++ b/actionpack/lib/action_view/template/partial.rb @@ -0,0 +1,18 @@ +module ActionView + # NOTE: The template that this mixin is being included into is frozen + # so you cannot set or modify any instance variables + module RenderablePartial #:nodoc: + extend ActiveSupport::Memoizable + + def variable_name + name.sub(/\A_/, '').to_sym + end + memoize :variable_name + + def counter_name + "#{variable_name}_counter".to_sym + end + memoize :counter_name + + end +end diff --git a/actionpack/lib/action_view/template/renderable.rb b/actionpack/lib/action_view/template/renderable.rb new file mode 100644 index 0000000000..35c832aaba --- /dev/null +++ b/actionpack/lib/action_view/template/renderable.rb @@ -0,0 +1,74 @@ +module ActionView + # NOTE: The template that this mixin is being included into is frozen + # so you cannot set or modify any instance variables + module Renderable #:nodoc: + extend ActiveSupport::Memoizable + + def filename + 'compiled-template' + end + + def handler + Template.handler_class_for_extension(extension) + end + memoize :handler + + def compiled_source + handler.call(self) + end + memoize :compiled_source + + def method_name_without_locals + ['_run', extension, method_segment].compact.join('_') + end + memoize :method_name_without_locals + + def method_name(local_assigns) + if local_assigns && local_assigns.any? + method_name = method_name_without_locals.dup + method_name << "_locals_#{local_assigns.keys.map { |k| k.to_s }.sort.join('_')}" + else + method_name = method_name_without_locals + end + method_name.to_sym + end + + # Compile and evaluate the template's code (if necessary) + def compile(local_assigns) + render_symbol = method_name(local_assigns) + + if !Base::CompiledTemplates.method_defined?(render_symbol) || recompile? + compile!(render_symbol, local_assigns) + end + end + + private + def compile!(render_symbol, local_assigns) + locals_code = local_assigns.keys.map { |key| "#{key} = local_assigns[:#{key}];" }.join + + source = <<-end_src + def #{render_symbol}(local_assigns) + old_output_buffer = output_buffer;#{locals_code};#{compiled_source} + ensure + self.output_buffer = old_output_buffer + end + end_src + + begin + ActionView::Base::CompiledTemplates.module_eval(source, filename, 0) + rescue Exception => e # errors from template code + if logger = defined?(ActionController) && Base.logger + logger.debug "ERROR: compiling #{render_symbol} RAISED #{e}" + logger.debug "Function body: #{source}" + logger.debug "Backtrace: #{e.backtrace.join("\n")}" + end + + raise ActionView::TemplateError.new(self, {}, e) + end + end + + def recompile? + false + end + end +end diff --git a/actionpack/lib/action_view/template/template.rb b/actionpack/lib/action_view/template/template.rb new file mode 100644 index 0000000000..235a95a0f3 --- /dev/null +++ b/actionpack/lib/action_view/template/template.rb @@ -0,0 +1,241 @@ +module ActionView #:nodoc: + class Template + class Path + attr_reader :path, :paths + delegate :hash, :inspect, :to => :path + + def initialize(path) + raise ArgumentError, "path already is a Path class" if path.is_a?(Path) + @path = path.freeze + end + + def to_s + if defined?(RAILS_ROOT) + path.to_s.sub(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') + else + path.to_s + end + end + + def to_str + path.to_str + end + + def ==(path) + to_str == path.to_str + end + + def eql?(path) + to_str == path.to_str + end + + # Returns a ActionView::Template object for the given path string. The + # input path should be relative to the view path directory, + # +hello/index.html.erb+. This method also has a special exception to + # match partial file names without a handler extension. So + # +hello/index.html+ will match the first template it finds with a + # known template extension, +hello/index.html.erb+. Template extensions + # should not be confused with format extensions +html+, +js+, +xml+, + # etc. A format must be supplied to match a formated file. +hello/index+ + # will never match +hello/index.html.erb+. + def find_template(path) + templates_in_path do |template| + if template.accessible_paths.include?(path) + return template + end + end + nil + end + + def find_by_parts(name, extensions = nil, prefix = nil, partial = nil) + path = prefix ? "#{prefix}/" : "" + + name = name.split("/") + name[-1] = "_#{name[-1]}" if partial + + path << name.join("/") + + template = nil + + Array(extensions).each do |extension| + extensioned_path = extension ? "#{path}.#{extension}" : path + template = find_template(extensioned_path) || find_template(path) + break if template + end + template + end + + private + def templates_in_path + (Dir.glob("#{@path}/**/*/**") | Dir.glob("#{@path}/**")).each do |file| + yield create_template(file) unless File.directory?(file) + end + end + + def create_template(file) + Template.new(file.split("#{self}/").last, self) + end + end + + class EagerPath < Path + def initialize(path) + super + + @paths = {} + templates_in_path do |template| + template.load! + template.accessible_paths.each do |path| + @paths[path] = template + end + end + @paths.freeze + end + + def find_template(path) + @paths[path] + end + end + + extend TemplateHandlers + extend ActiveSupport::Memoizable + include Renderable + + # Templates that are exempt from layouts + @@exempt_from_layout = Set.new([/\.rjs$/]) + + # Don't render layouts for templates with the given extensions. + def self.exempt_from_layout(*extensions) + regexps = extensions.collect do |extension| + extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/ + end + @@exempt_from_layout.merge(regexps) + end + + attr_accessor :filename, :load_path, :base_path, :name, :format, :extension + delegate :to_s, :to => :path + + def initialize(template_path, load_paths = []) + template_path = template_path.dup + @load_path, @filename = find_full_path(template_path, load_paths) + @base_path, @name, @format, @extension = split(template_path) + @base_path.to_s.gsub!(/\/$/, '') # Push to split method + + # Extend with partial super powers + extend RenderablePartial if @name =~ /^_/ + end + + def accessible_paths + paths = [] + paths << path + paths << path_without_extension + if multipart? + formats = format.split(".") + paths << "#{path_without_format_and_extension}.#{formats.first}" + paths << "#{path_without_format_and_extension}.#{formats.second}" + end + paths + end + + def format_and_extension + (extensions = [format, extension].compact.join(".")).blank? ? nil : extensions + end + memoize :format_and_extension + + def multipart? + format && format.include?('.') + end + + def content_type + format.gsub('.', '/') + end + + def mime_type + Mime::Type.lookup_by_extension(format) if format + end + memoize :mime_type + + def path + [base_path, [name, format, extension].compact.join('.')].compact.join('/') + end + memoize :path + + def path_without_extension + [base_path, [name, format].compact.join('.')].compact.join('/') + end + memoize :path_without_extension + + def path_without_format_and_extension + [base_path, name].compact.join('/') + end + memoize :path_without_format_and_extension + + def relative_path + path = File.expand_path(filename) + path.sub!(/^#{Regexp.escape(File.expand_path(RAILS_ROOT))}\//, '') if defined?(RAILS_ROOT) + path + end + memoize :relative_path + + def exempt_from_layout? + @@exempt_from_layout.any? { |exempted| path =~ exempted } + end + + def mtime + File.mtime(filename) + end + memoize :mtime + + def source + File.read(filename) + end + memoize :source + + def method_segment + relative_path.to_s.gsub(/([^a-zA-Z0-9_])/) { $1.ord } + end + memoize :method_segment + + def stale? + File.mtime(filename) > mtime + end + + def recompile? + !@cached + end + + def load! + @cached = true + freeze + end + + private + def valid_extension?(extension) + !Template.registered_template_handler(extension).nil? + end + + def find_full_path(path, load_paths) + load_paths = Array(load_paths) + [nil] + load_paths.each do |load_path| + file = load_path ? "#{load_path.to_str}/#{path}" : path + return load_path, file if File.file?(file) + end + raise MissingTemplate.new(load_paths, path) + end + + # Returns file split into an array + # [base_path, name, format, extension] + def split(file) + if m = file.match(/^(.*\/)?([^\.]+)\.?(\w+)?\.?(\w+)?\.?(\w+)?$/) + if valid_extension?(m[5]) # Multipart formats + [m[1], m[2], "#{m[3]}.#{m[4]}", m[5]] + elsif valid_extension?(m[4]) # Single format + [m[1], m[2], m[3], m[4]] + elsif valid_extension?(m[3]) # No format + [m[1], m[2], nil, m[3]] + else # No extension + [m[1], m[2], m[3], nil] + end + end + end + end +end diff --git a/actionpack/lib/action_view/template_error.rb b/actionpack/lib/action_view/template_error.rb deleted file mode 100644 index 37cb1c7c6c..0000000000 --- a/actionpack/lib/action_view/template_error.rb +++ /dev/null @@ -1,99 +0,0 @@ -module ActionView - # The TemplateError exception is raised when the compilation of the template fails. This exception then gathers a - # bunch of intimate details and uses it to report a very precise exception message. - class TemplateError < ActionViewError #:nodoc: - SOURCE_CODE_RADIUS = 3 - - attr_reader :original_exception - - def initialize(template, assigns, original_exception) - @template, @assigns, @original_exception = template, assigns.dup, original_exception - @backtrace = compute_backtrace - end - - def file_name - @template.relative_path - end - - def message - ActiveSupport::Deprecation.silence { original_exception.message } - end - - def clean_backtrace - if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner) - Rails.backtrace_cleaner.clean(original_exception.backtrace) - else - original_exception.backtrace - end - end - - def sub_template_message - if @sub_templates - "Trace of template inclusion: " + - @sub_templates.collect { |template| template.relative_path }.join(", ") - else - "" - end - end - - def source_extract(indentation = 0) - return unless num = line_number - num = num.to_i - - source_code = @template.source.split("\n") - - start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max - end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min - - indent = ' ' * indentation - line_counter = start_on_line - return unless source_code = source_code[start_on_line..end_on_line] - - source_code.sum do |line| - line_counter += 1 - "#{indent}#{line_counter}: #{line}\n" - end - end - - def sub_template_of(template_path) - @sub_templates ||= [] - @sub_templates << template_path - end - - def line_number - @line_number ||= - if file_name - regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/ - - $1 if message =~ regexp or clean_backtrace.find { |line| line =~ regexp } - end - end - - def to_s - "\n#{self.class} (#{message}) #{source_location}:\n" + - "#{source_extract}\n #{clean_backtrace.join("\n ")}\n\n" - end - - # don't do anything nontrivial here. Any raised exception from here becomes fatal - # (and can't be rescued). - def backtrace - @backtrace - end - - private - def compute_backtrace - [ - "#{source_location.capitalize}\n\n#{source_extract(4)}\n " + - clean_backtrace.join("\n ") - ] - end - - def source_location - if line_number - "on line ##{line_number} of " - else - 'in ' - end + file_name - end - end -end \ No newline at end of file diff --git a/actionpack/lib/action_view/template_handler.rb b/actionpack/lib/action_view/template_handler.rb deleted file mode 100644 index 672da0ed2b..0000000000 --- a/actionpack/lib/action_view/template_handler.rb +++ /dev/null @@ -1,34 +0,0 @@ -# Legacy TemplateHandler stub -module ActionView - module TemplateHandlers #:nodoc: - module Compilable - def self.included(base) - base.extend(ClassMethods) - end - - module ClassMethods - def call(template) - new.compile(template) - end - end - - def compile(template) - raise "Need to implement #{self.class.name}#compile(template)" - end - end - end - - class TemplateHandler - def self.call(template) - "#{name}.new(self).render(template, local_assigns)" - end - - def initialize(view = nil) - @view = view - end - - def render(template, local_assigns) - raise "Need to implement #{self.class.name}#render(template, local_assigns)" - end - end -end diff --git a/actionpack/lib/action_view/template_handlers.rb b/actionpack/lib/action_view/template_handlers.rb deleted file mode 100644 index 205f8628f0..0000000000 --- a/actionpack/lib/action_view/template_handlers.rb +++ /dev/null @@ -1,48 +0,0 @@ -module ActionView #:nodoc: - module TemplateHandlers #:nodoc: - autoload :ERB, 'action_view/template_handlers/erb' - autoload :RJS, 'action_view/template_handlers/rjs' - autoload :Builder, 'action_view/template_handlers/builder' - - def self.extended(base) - base.register_default_template_handler :erb, TemplateHandlers::ERB - base.register_template_handler :rjs, TemplateHandlers::RJS - base.register_template_handler :builder, TemplateHandlers::Builder - - # TODO: Depreciate old template extensions - base.register_template_handler :rhtml, TemplateHandlers::ERB - base.register_template_handler :rxml, TemplateHandlers::Builder - end - - @@template_handlers = {} - @@default_template_handlers = nil - - # Register a class that knows how to handle template files with the given - # extension. This can be used to implement new template types. - # The constructor for the class must take the ActiveView::Base instance - # as a parameter, and the class must implement a +render+ method that - # takes the contents of the template to render as well as the Hash of - # local assigns available to the template. The +render+ method ought to - # return the rendered template as a string. - def register_template_handler(extension, klass) - @@template_handlers[extension.to_sym] = klass - end - - def template_handler_extensions - @@template_handlers.keys.map(&:to_s).sort - end - - def registered_template_handler(extension) - extension && @@template_handlers[extension.to_sym] - end - - def register_default_template_handler(extension, klass) - register_template_handler(extension, klass) - @@default_template_handlers = klass - end - - def handler_class_for_extension(extension) - registered_template_handler(extension) || @@default_template_handlers - end - end -end diff --git a/actionpack/lib/action_view/template_handlers/builder.rb b/actionpack/lib/action_view/template_handlers/builder.rb deleted file mode 100644 index 788dc93326..0000000000 --- a/actionpack/lib/action_view/template_handlers/builder.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'builder' - -module ActionView - module TemplateHandlers - class Builder < TemplateHandler - include Compilable - - def compile(template) - "_set_controller_content_type(Mime::XML);" + - "xml = ::Builder::XmlMarkup.new(:indent => 2);" + - "self.output_buffer = xml.target!;" + - template.source + - ";xml.target!;" - end - end - end -end diff --git a/actionpack/lib/action_view/template_handlers/erb.rb b/actionpack/lib/action_view/template_handlers/erb.rb deleted file mode 100644 index e3120ba267..0000000000 --- a/actionpack/lib/action_view/template_handlers/erb.rb +++ /dev/null @@ -1,22 +0,0 @@ -module ActionView - module TemplateHandlers - class ERB < TemplateHandler - include Compilable - - ## - # :singleton-method: - # Specify trim mode for the ERB compiler. Defaults to '-'. - # See ERb documentation for suitable values. - cattr_accessor :erb_trim_mode - self.erb_trim_mode = '-' - - def compile(template) - src = ::ERB.new("<% __in_erb_template=true %>#{template.source}", nil, erb_trim_mode, '@output_buffer').src - - # Ruby 1.9 prepends an encoding to the source. However this is - # useless because you can only set an encoding on the first line - RUBY_VERSION >= '1.9' ? src.sub(/\A#coding:.*\n/, '') : src - end - end - end -end diff --git a/actionpack/lib/action_view/template_handlers/rjs.rb b/actionpack/lib/action_view/template_handlers/rjs.rb deleted file mode 100644 index 41a1fddb47..0000000000 --- a/actionpack/lib/action_view/template_handlers/rjs.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActionView - module TemplateHandlers - class RJS < TemplateHandler - include Compilable - - def compile(template) - "@template_format = :html;" + - "controller.response.content_type ||= Mime::JS;" + - "update_page do |page|;#{template.source}\nend" - end - end - end -end diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index ec337bb05b..c8f204046b 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -7,18 +7,15 @@ module ActionView @_rendered = { :template => nil, :partials => Hash.new(0) } initialize_without_template_tracking(*args) end - end - - module Renderable - alias_method :render_without_template_tracking, :render - def render(view, local_assigns = {}) - if respond_to?(:path) && !is_a?(InlineTemplate) - rendered = view.instance_variable_get(:@_rendered) - rendered[:partials][self] += 1 if is_a?(RenderablePartial) - rendered[:template] ||= self + + alias_method :_render_template_without_template_tracking, :_render_template + def _render_template(template, local_assigns = {}) + if template.respond_to?(:path) && !template.is_a?(InlineTemplate) + @_rendered[:partials][template] += 1 if template.is_a?(RenderablePartial) + @_rendered[:template] ||= template end - render_without_template_tracking(view, local_assigns) - end + _render_template_without_template_tracking(template, local_assigns) + end end class TestCase < ActiveSupport::TestCase -- cgit v1.2.3 From a0f2b1d95d3785de92ae271fd7ea23e91c0cadc6 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Tue, 27 Jan 2009 18:17:39 -0600 Subject: Reorganize ActionController folder structure --- actionpack/lib/action_view/render/partials.rb | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'actionpack/lib/action_view') diff --git a/actionpack/lib/action_view/render/partials.rb b/actionpack/lib/action_view/render/partials.rb index aa4c4af213..e337dcb63b 100644 --- a/actionpack/lib/action_view/render/partials.rb +++ b/actionpack/lib/action_view/render/partials.rb @@ -243,6 +243,34 @@ module ActionView end end + def _render_partial_with_block(layout, block, options) + @_proc_for_layout = block + concat(_render_partial(options.merge(:partial => layout))) + ensure + @_proc_for_layout = nil + end + + def _render_partial_with_layout(layout, options) + if layout + prefix = controller && !layout.include?("/") ? controller.controller_path : nil + layout = find_by_parts(layout, formats, prefix, true) + end + content = _render_partial(options) + return _render_content_with_layout(content, layout, options[:locals]) + end + + def _deprecated_ivar_assign(template) + if respond_to?(:controller) + ivar = :"@#{template.variable_name}" + object = + if controller.instance_variable_defined?(ivar) + ActiveSupport::Deprecation::DeprecatedObjectProxy.new( + controller.instance_variable_get(ivar), + "#{ivar} will no longer be implicitly assigned to #{template.variable_name}") + end + end + end + def _array_like_objects array_like = [Array] if defined?(ActiveRecord) -- cgit v1.2.3