diff options
Diffstat (limited to 'actionview')
60 files changed, 569 insertions, 273 deletions
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index 5e7b271fb9..2e6c37de58 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,5 @@ +## Rails 6.0.0.beta2 (February 25, 2019) ## + * ActionView::Template.finalize_compiled_template_methods is deprecated with no replacement. diff --git a/actionview/README.rdoc b/actionview/README.rdoc index 03a0723564..ba50c67024 100644 --- a/actionview/README.rdoc +++ b/actionview/README.rdoc @@ -5,6 +5,8 @@ view helpers that assist when building HTML forms, Atom feeds and more. Template formats that Action View handles are ERB (embedded Ruby, typically used to inline short Ruby snippets inside HTML), and XML Builder. +You can read more about Action View in the {Action View Overview}[https://edgeguides.rubyonrails.org/action_view_overview.html] guide. + == Download and installation The latest version of Action View can be installed with RubyGems: @@ -27,7 +29,7 @@ Action View is released under the MIT license: API documentation is at -* http://api.rubyonrails.org +* https://api.rubyonrails.org Bug reports for the Ruby on Rails project can be filed here: diff --git a/actionview/actionview.gemspec b/actionview/actionview.gemspec index d8bd233ceb..200c775dcc 100644 --- a/actionview/actionview.gemspec +++ b/actionview/actionview.gemspec @@ -15,7 +15,7 @@ Gem::Specification.new do |s| s.author = "David Heinemeier Hansson" s.email = "david@loudthinking.com" - s.homepage = "http://rubyonrails.org" + s.homepage = "https://rubyonrails.org" s.files = Dir["CHANGELOG.md", "README.rdoc", "MIT-LICENSE", "lib/**/*"] s.require_path = "lib" diff --git a/actionview/app/assets/javascripts/README.md b/actionview/app/assets/javascripts/README.md index b9682b61e2..aa167004b6 100644 --- a/actionview/app/assets/javascripts/README.md +++ b/actionview/app/assets/javascripts/README.md @@ -52,5 +52,5 @@ Run `bundle exec rake ujs:server` first, and then run the web tests by visiting rails-ujs is released under the [MIT License](MIT-LICENSE). [data]: https://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-attributes "Embedding custom non-visible data with the data-* attributes" -[validator]: http://validator.w3.org/ -[csrf]: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html +[validator]: https://validator.w3.org/ +[csrf]: https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html diff --git a/actionview/app/assets/javascripts/rails-ujs/start.coffee b/actionview/app/assets/javascripts/rails-ujs/start.coffee index 5c1214df59..0347058195 100644 --- a/actionview/app/assets/javascripts/rails-ujs/start.coffee +++ b/actionview/app/assets/javascripts/rails-ujs/start.coffee @@ -2,6 +2,7 @@ fire, delegate getData, $ refreshCSRFTokens, CSRFProtection + loadCSPNonce enableElement, disableElement, handleDisabledElement handleConfirm, preventInsignificantClick handleRemote, formSubmitButtonClick, @@ -67,6 +68,7 @@ Rails.start = -> delegate document, Rails.formInputClickSelector, 'click', formSubmitButtonClick document.addEventListener('DOMContentLoaded', refreshCSRFTokens) + document.addEventListener('DOMContentLoaded', loadCSPNonce) window._rails_loaded = true if window.Rails is Rails and fire(document, 'rails:attachBindings') diff --git a/actionview/app/assets/javascripts/rails-ujs/utils/csp.coffee b/actionview/app/assets/javascripts/rails-ujs/utils/csp.coffee index 8d2d6ce447..a33f531375 100644 --- a/actionview/app/assets/javascripts/rails-ujs/utils/csp.coffee +++ b/actionview/app/assets/javascripts/rails-ujs/utils/csp.coffee @@ -1,4 +1,8 @@ -# Content-Security-Policy nonce for inline scripts -cspNonce = Rails.cspNonce = -> - meta = document.querySelector('meta[name=csp-nonce]') - meta and meta.content +nonce = null + +Rails.loadCSPNonce = -> + nonce = document.querySelector("meta[name=csp-nonce]")?.content + +# Returns the Content-Security-Policy nonce for inline scripts. +Rails.cspNonce = -> + nonce ? Rails.loadCSPNonce() diff --git a/actionview/app/assets/javascripts/rails-ujs/utils/event.coffee b/actionview/app/assets/javascripts/rails-ujs/utils/event.coffee index a7eee52060..768d9683d4 100644 --- a/actionview/app/assets/javascripts/rails-ujs/utils/event.coffee +++ b/actionview/app/assets/javascripts/rails-ujs/utils/event.coffee @@ -27,7 +27,7 @@ if typeof CustomEvent isnt 'function' # obj:: # a native DOM element # name:: -# string that corrspends to the event you want to trigger +# string that corresponds to the event you want to trigger # e.g. 'click', 'submit' # data:: # data you want to pass when you dispatch an event diff --git a/actionview/lib/action_view/base.rb b/actionview/lib/action_view/base.rb index 420136d6de..c4565ca272 100644 --- a/actionview/lib/action_view/base.rb +++ b/actionview/lib/action_view/base.rb @@ -196,10 +196,9 @@ module ActionView #:nodoc: end end - attr_reader :view_renderer + attr_reader :view_renderer, :lookup_context attr_internal :config, :assigns - delegate :lookup_context, to: :view_renderer delegate :formats, :formats=, :locale, :locale=, :view_paths, :view_paths=, to: :lookup_context def assign(new_assigns) # :nodoc: @@ -208,12 +207,19 @@ module ActionView #:nodoc: # :stopdoc: - def self.build_renderer(context, controller, formats) - lookup_context = context.is_a?(ActionView::LookupContext) ? - context : ActionView::LookupContext.new(context) - lookup_context.formats = formats if formats - lookup_context.prefixes = controller._prefixes if controller - ActionView::Renderer.new(lookup_context) + def self.build_lookup_context(context) + case context + when ActionView::Renderer + context.lookup_context + when Array + ActionView::LookupContext.new(context) + when ActionView::PathSet + ActionView::LookupContext.new(context) + when nil + ActionView::LookupContext.new([]) + else + raise NotImplementedError, context.class.name + end end def self.empty @@ -225,54 +231,80 @@ module ActionView #:nodoc: end def self.with_context(context, assigns = {}, controller = nil) - new ActionView::Renderer.new(context), assigns, controller + new context, assigns, controller end NULL = Object.new # :startdoc: - def initialize(renderer = nil, assigns = {}, controller = nil, formats = NULL) #:nodoc: + def initialize(lookup_context = nil, assigns = {}, controller = nil, formats = NULL) #:nodoc: @_config = ActiveSupport::InheritableOptions.new - if formats == NULL - formats = nil - else + unless formats == NULL ActiveSupport::Deprecation.warn <<~eowarn Passing formats to ActionView::Base.new is deprecated eowarn end - if renderer.is_a?(ActionView::Renderer) - @view_renderer = renderer + case lookup_context + when ActionView::LookupContext + @lookup_context = lookup_context else ActiveSupport::Deprecation.warn <<~eowarn - ActionView::Base instances should be constructed with a view renderer, - assigments, and a controller. + ActionView::Base instances should be constructed with a lookup context, + assignments, and a controller. eowarn - @view_renderer = self.class.build_renderer(renderer, controller, formats) + @lookup_context = self.class.build_lookup_context(lookup_context) end + @view_renderer = ActionView::Renderer.new @lookup_context + @current_template = nil + @cache_hit = {} assign(assigns) assign_controller(controller) _prepare_context end - def run(method, locals, buffer, &block) - _old_output_buffer, _old_virtual_path = @output_buffer, @virtual_path + def run(method, template, locals, buffer, &block) + _old_output_buffer, _old_virtual_path, _old_template = @output_buffer, @virtual_path, @current_template + @current_template = template @output_buffer = buffer send(method, locals, buffer, &block) ensure - @output_buffer, @virtual_path = _old_output_buffer, _old_virtual_path + @output_buffer, @virtual_path, @current_template = _old_output_buffer, _old_virtual_path, _old_template end def compiled_method_container - raise NotImplementedError, <<~msg - Subclasses of ActionView::Base must implement `compiled_method_container` - or use the class method `with_empty_template_cache` for constructing - an ActionView::Base subclass that has an empty cache. - msg + if self.class == ActionView::Base + ActiveSupport::Deprecation.warn <<~eowarn + ActionView::Base instances must implement `compiled_method_container` + or use the class method `with_empty_template_cache` for constructing + an ActionView::Base instances that has an empty cache. + eowarn + end + + self.class + end + + def in_rendering_context(options) + old_view_renderer = @view_renderer + old_lookup_context = @lookup_context + + if !lookup_context.html_fallback_for_js && options[:formats] + formats = Array(options[:formats]) + if formats == [:js] + formats << :html + end + @lookup_context = lookup_context.with_prepended_formats(formats) + @view_renderer = ActionView::Renderer.new @lookup_context + end + + yield @view_renderer + ensure + @view_renderer = old_view_renderer + @lookup_context = old_lookup_context end ActiveSupport.run_load_hooks(:action_view, self) diff --git a/actionview/lib/action_view/digestor.rb b/actionview/lib/action_view/digestor.rb index 6d2e471a44..9fa8d7eab1 100644 --- a/actionview/lib/action_view/digestor.rb +++ b/actionview/lib/action_view/digestor.rb @@ -18,11 +18,11 @@ module ActionView # * <tt>name</tt> - Template name # * <tt>finder</tt> - An instance of <tt>ActionView::LookupContext</tt> # * <tt>dependencies</tt> - An array of dependent views - def digest(name:, finder:, dependencies: nil) + def digest(name:, format:, finder:, dependencies: nil) if dependencies.nil? || dependencies.empty? - cache_key = "#{name}.#{finder.rendered_format}" + cache_key = "#{name}.#{format}" else - cache_key = [ name, finder.rendered_format, dependencies ].flatten.compact.join(".") + cache_key = [ name, format, dependencies ].flatten.compact.join(".") end # this is a correctly done double-checked locking idiom @@ -48,8 +48,6 @@ module ActionView logical_name = name.gsub(%r|/_|, "/") if template = find_template(finder, logical_name, [], partial, []) - finder.rendered_format ||= template.formats.first - if node = seen[template.identifier] # handle cycles in the tree node else @@ -73,9 +71,7 @@ module ActionView private def find_template(finder, name, prefixes, partial, keys) finder.disable_cache do - format = finder.rendered_format - result = finder.find_all(name, prefixes, partial, keys, formats: [format]).first if format - result || finder.find_all(name, prefixes, partial, keys).first + finder.find_all(name, prefixes, partial, keys).first end end end diff --git a/actionview/lib/action_view/file_template.rb b/actionview/lib/action_view/file_template.rb index 4921074383..dea02176eb 100644 --- a/actionview/lib/action_view/file_template.rb +++ b/actionview/lib/action_view/file_template.rb @@ -22,11 +22,11 @@ module ActionView # to ensure that references to the template object can be marshalled as well. This means forgoing # the marshalling of the compiler mutex and instantiating that again on unmarshalling. def marshal_dump # :nodoc: - [ @identifier, @handler, @compiled, @original_encoding, @locals, @virtual_path, @updated_at, @formats, @variants ] + [ @identifier, @handler, @compiled, @locals, @virtual_path, @updated_at, @format, @variant ] end def marshal_load(array) # :nodoc: - @identifier, @handler, @compiled, @original_encoding, @locals, @virtual_path, @updated_at, @formats, @variants = *array + @identifier, @handler, @compiled, @locals, @virtual_path, @updated_at, @format, @variant = *array @compile_mutex = Mutex.new end end diff --git a/actionview/lib/action_view/gem_version.rb b/actionview/lib/action_view/gem_version.rb index 02de3eeec2..c799967cc5 100644 --- a/actionview/lib/action_view/gem_version.rb +++ b/actionview/lib/action_view/gem_version.rb @@ -10,7 +10,7 @@ module ActionView MAJOR = 6 MINOR = 0 TINY = 0 - PRE = "beta1" + PRE = "beta2" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/actionview/lib/action_view/helpers/cache_helper.rb b/actionview/lib/action_view/helpers/cache_helper.rb index b1a14250c3..020aebeea3 100644 --- a/actionview/lib/action_view/helpers/cache_helper.rb +++ b/actionview/lib/action_view/helpers/cache_helper.rb @@ -216,13 +216,13 @@ module ActionView end end - def digest_path_from_virtual(virtual_path) # :nodoc: - digest = Digestor.digest(name: virtual_path, finder: lookup_context, dependencies: view_cache_dependencies) + def digest_path_from_template(template) # :nodoc: + digest = Digestor.digest(name: template.virtual_path, format: template.format, finder: lookup_context, dependencies: view_cache_dependencies) if digest.present? - "#{virtual_path}:#{digest}" + "#{template.virtual_path}:#{digest}" else - virtual_path + template.virtual_path end end @@ -234,7 +234,7 @@ module ActionView if virtual_path || digest_path name = controller.url_for(name).split("://").last if name.is_a?(Hash) - digest_path ||= digest_path_from_virtual(virtual_path) + digest_path ||= digest_path_from_template(@current_template) [ digest_path, name ] else diff --git a/actionview/lib/action_view/helpers/csp_helper.rb b/actionview/lib/action_view/helpers/csp_helper.rb index e2e065c218..4415018845 100644 --- a/actionview/lib/action_view/helpers/csp_helper.rb +++ b/actionview/lib/action_view/helpers/csp_helper.rb @@ -14,9 +14,11 @@ module ActionView # This is used by the Rails UJS helper to create dynamically # loaded inline <script> elements. # - def csp_meta_tag + def csp_meta_tag(**options) if content_security_policy? - tag("meta", name: "csp-nonce", content: content_security_policy_nonce) + options[:name] = "csp-nonce" + options[:content] = content_security_policy_nonce + tag("meta", options) end end end diff --git a/actionview/lib/action_view/helpers/output_safety_helper.rb b/actionview/lib/action_view/helpers/output_safety_helper.rb index 279cde5e76..52a951b2ca 100644 --- a/actionview/lib/action_view/helpers/output_safety_helper.rb +++ b/actionview/lib/action_view/helpers/output_safety_helper.rb @@ -38,7 +38,7 @@ module ActionView #:nodoc: # Converts the array to a comma-separated sentence where the last element is # joined by the connector word. This is the html_safe-aware version of - # ActiveSupport's {Array#to_sentence}[http://api.rubyonrails.org/classes/Array.html#method-i-to_sentence]. + # ActiveSupport's {Array#to_sentence}[https://api.rubyonrails.org/classes/Array.html#method-i-to_sentence]. # def to_sentence(array, options = {}) options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale) diff --git a/actionview/lib/action_view/helpers/rendering_helper.rb b/actionview/lib/action_view/helpers/rendering_helper.rb index 1e12aa2736..7ead691113 100644 --- a/actionview/lib/action_view/helpers/rendering_helper.rb +++ b/actionview/lib/action_view/helpers/rendering_helper.rb @@ -27,10 +27,12 @@ module ActionView def render(options = {}, locals = {}, &block) case options when Hash - if block_given? - view_renderer.render_partial(self, options.merge(partial: options[:layout]), &block) - else - view_renderer.render(self, options) + in_rendering_context(options) do |renderer| + if block_given? + view_renderer.render_partial(self, options.merge(partial: options[:layout]), &block) + else + view_renderer.render(self, options) + end end else view_renderer.render_partial(self, partial: options, locals: locals, &block) diff --git a/actionview/lib/action_view/helpers/translation_helper.rb b/actionview/lib/action_view/helpers/translation_helper.rb index 67c86592b9..d5b0a9263f 100644 --- a/actionview/lib/action_view/helpers/translation_helper.rb +++ b/actionview/lib/action_view/helpers/translation_helper.rb @@ -114,7 +114,7 @@ module ActionView # Delegates to <tt>I18n.localize</tt> with no additional functionality. # - # See http://rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize + # See https://www.rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize # for more information. def localize(*args) I18n.localize(*args) @@ -138,7 +138,7 @@ module ActionView end def html_safe_translation_key?(key) - /([_.]|\b)html\z/.match?(key.to_s) + /(?:_|\b)html\z/.match?(key.to_s) end end end diff --git a/actionview/lib/action_view/layouts.rb b/actionview/lib/action_view/layouts.rb index 3e6d352c15..08f66bf435 100644 --- a/actionview/lib/action_view/layouts.rb +++ b/actionview/lib/action_view/layouts.rb @@ -322,7 +322,7 @@ module ActionView end class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def _layout(formats) + def _layout(lookup_context, formats) if _conditional_layout? #{layout_definition} else @@ -388,8 +388,8 @@ module ActionView case name when String then _normalize_layout(name) when Proc then name - when true then Proc.new { |formats| _default_layout(formats, true) } - when :default then Proc.new { |formats| _default_layout(formats, false) } + when true then Proc.new { |lookup_context, formats| _default_layout(lookup_context, formats, true) } + when :default then Proc.new { |lookup_context, formats| _default_layout(lookup_context, formats, false) } when false, nil then nil else raise ArgumentError, @@ -411,9 +411,9 @@ module ActionView # # ==== Returns # * <tt>template</tt> - The template object for the default layout (or +nil+) - def _default_layout(formats, require_layout = false) + def _default_layout(lookup_context, formats, require_layout = false) begin - value = _layout(formats) if action_has_layout? + value = _layout(lookup_context, formats) if action_has_layout? rescue NameError => e raise e, "Could not render layout: #{e.message}" end diff --git a/actionview/lib/action_view/lookup_context.rb b/actionview/lib/action_view/lookup_context.rb index 61fe11cf45..10cd61bbd6 100644 --- a/actionview/lib/action_view/lookup_context.rb +++ b/actionview/lib/action_view/lookup_context.rb @@ -16,6 +16,8 @@ module ActionView # only once during the request, it speeds up all cache accesses. class LookupContext #:nodoc: attr_accessor :prefixes, :rendered_format + deprecate :rendered_format + deprecate :rendered_format= mattr_accessor :fallbacks, default: FallbackFileSystemResolver.instances @@ -250,7 +252,6 @@ module ActionView @digest_cache = nil @cache = true @prefixes = prefixes - @rendered_format = nil @details = initialize_details({}, details) @view_paths = build_view_paths(view_paths) @@ -260,6 +261,13 @@ module ActionView @digest_cache ||= DetailsKey.digest_cache(@details) end + def with_prepended_formats(formats) + details = @details.dup + details[:formats] = formats + + self.class.new(@view_paths, details, @prefixes) + end + def initialize_details(target, details) registered_details.each do |k| target[k] = details[k] || Accessors::DEFAULT_PROCS[k].call diff --git a/actionview/lib/action_view/renderer/abstract_renderer.rb b/actionview/lib/action_view/renderer/abstract_renderer.rb index ae366ce54a..475452f1bb 100644 --- a/actionview/lib/action_view/renderer/abstract_renderer.rb +++ b/actionview/lib/action_view/renderer/abstract_renderer.rb @@ -27,6 +27,53 @@ module ActionView raise NotImplementedError end + class RenderedCollection # :nodoc: + def self.empty(format) + EmptyCollection.new format + end + + attr_reader :rendered_templates + + def initialize(rendered_templates, spacer) + @rendered_templates = rendered_templates + @spacer = spacer + end + + def body + @rendered_templates.map(&:body).join(@spacer.body).html_safe + end + + def format + rendered_templates.first.format + end + + class EmptyCollection + attr_reader :format + + def initialize(format) + @format = format + end + + def body; nil; end + end + end + + class RenderedTemplate # :nodoc: + attr_reader :body, :layout, :template + + def initialize(body, layout, template) + @body = body + @layout = layout + @template = template + end + + def format + template.format + end + + EMPTY_SPACER = Struct.new(:body).new + end + private def extract_details(options) # :doc: @@ -49,5 +96,13 @@ module ActionView @lookup_context.formats = formats | @lookup_context.formats end + + def build_rendered_template(content, template, layout = nil) + RenderedTemplate.new content, layout, template + end + + def build_rendered_collection(templates, spacer) + RenderedCollection.new templates, spacer + end end end diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb index 801916954f..ed8d5cf54e 100644 --- a/actionview/lib/action_view/renderer/partial_renderer.rb +++ b/actionview/lib/action_view/renderer/partial_renderer.rb @@ -308,15 +308,10 @@ module ActionView template = find_partial(@path, @template_keys) @variable ||= template.variable else - template = nil - end - - @lookup_context.rendered_format ||= begin - if template && template.formats.first - template.formats.first - else - formats.first + if options[:cached] + raise NotImplementedError, "render caching requires a template. Please specify a partial when rendering" end + template = nil end if @collection @@ -331,15 +326,23 @@ module ActionView def render_collection(view, template) identifier = (template && template.identifier) || @path instrument(:collection, identifier: identifier, count: @collection.size) do |payload| - return nil if @collection.blank? + return RenderedCollection.empty(@lookup_context.formats.first) if @collection.blank? - if @options.key?(:spacer_template) - spacer = find_template(@options[:spacer_template], @locals.keys).render(view, @locals) + spacer = if @options.key?(:spacer_template) + spacer_template = find_template(@options[:spacer_template], @locals.keys) + build_rendered_template(spacer_template.render(view, @locals), spacer_template) + else + RenderedTemplate::EMPTY_SPACER end - cache_collection_render(payload, view, template) do - template ? collection_with_template(view, template) : collection_without_template(view) - end.join(spacer).html_safe + collection_body = if template + cache_collection_render(payload, view, template) do + collection_with_template(view, template) + end + else + collection_without_template(view) + end + build_rendered_collection(collection_body, spacer) end end @@ -361,7 +364,7 @@ module ActionView content = layout.render(view, locals) { content } if layout payload[:cache_hit] = view.view_renderer.cache_hits[template.virtual_path] - content + build_rendered_template(content, template, layout) end end @@ -379,8 +382,6 @@ module ActionView @locals = options[:locals] || {} @details = extract_details(options) - prepend_formats(options[:formats]) - partial = options[:partial] if String === partial @@ -454,7 +455,7 @@ module ActionView content = template.render(view, locals) content = layout.render(view, locals) { content } if layout partial_iteration.iterate! - content + build_rendered_template(content, template, layout) end end @@ -476,7 +477,7 @@ module ActionView template = (cache[path] ||= find_template(path, keys + [as, counter, iteration])) content = template.render(view, locals) partial_iteration.iterate! - content + build_rendered_template(content, template) end end diff --git a/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb b/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb index 388f9e5e56..ed59033e27 100644 --- a/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb +++ b/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb @@ -40,7 +40,7 @@ module ActionView rendered_partials = @collection.empty? ? [] : yield index = 0 - fetch_or_cache_partial(cached_partials, order_by: keyed_collection.each_key) do + fetch_or_cache_partial(cached_partials, template, order_by: keyed_collection.each_key) do # This block is called once # for every cache miss while preserving order. rendered_partials[index].tap { index += 1 } @@ -54,7 +54,7 @@ module ActionView def collection_by_cache_keys(view, template) seed = callable_cache_key? ? @options[:cached] : ->(i) { i } - digest_path = view.digest_path_from_virtual(template.virtual_path) + digest_path = view.digest_path_from_template(template) @collection.each_with_object({}) do |item, hash| hash[expanded_cache_key(seed.call(item), view, template, digest_path)] = item @@ -81,11 +81,13 @@ module ActionView # # If the partial is not already cached it will also be # written back to the underlying cache store. - def fetch_or_cache_partial(cached_partials, order_by:) + def fetch_or_cache_partial(cached_partials, template, order_by:) order_by.map do |cache_key| - cached_partials.fetch(cache_key) do + if content = cached_partials[cache_key] + build_rendered_template(content, template) + else yield.tap do |rendered_partial| - collection_cache.write(cache_key, rendered_partial) + collection_cache.write(cache_key, rendered_partial.body) end end end diff --git a/actionview/lib/action_view/renderer/renderer.rb b/actionview/lib/action_view/renderer/renderer.rb index 3f3a97529d..485eb1a5b4 100644 --- a/actionview/lib/action_view/renderer/renderer.rb +++ b/actionview/lib/action_view/renderer/renderer.rb @@ -19,10 +19,14 @@ module ActionView # Main render entry point shared by Action View and Action Controller. def render(context, options) + render_to_object(context, options).body + end + + def render_to_object(context, options) # :nodoc: if options.key?(:partial) - render_partial(context, options) + render_partial_to_object(context, options) else - render_template(context, options) + render_template_to_object(context, options) end end @@ -41,16 +45,24 @@ module ActionView # Direct access to template rendering. def render_template(context, options) #:nodoc: - TemplateRenderer.new(@lookup_context).render(context, options) + render_template_to_object(context, options).body end # Direct access to partial rendering. def render_partial(context, options, &block) #:nodoc: - PartialRenderer.new(@lookup_context).render(context, options, block) + render_partial_to_object(context, options, &block).body end def cache_hits # :nodoc: @cache_hits ||= {} end + + def render_template_to_object(context, options) #:nodoc: + TemplateRenderer.new(@lookup_context).render(context, options) + end + + def render_partial_to_object(context, options, &block) #:nodoc: + PartialRenderer.new(@lookup_context).render(context, options, block) + end end end diff --git a/actionview/lib/action_view/renderer/streaming_template_renderer.rb b/actionview/lib/action_view/renderer/streaming_template_renderer.rb index f414620923..279ef3c680 100644 --- a/actionview/lib/action_view/renderer/streaming_template_renderer.rb +++ b/actionview/lib/action_view/renderer/streaming_template_renderer.rb @@ -44,7 +44,7 @@ module ActionView # object that responds to each. This object is initialized with a block # that knows how to render the template. def render_template(view, template, layout_name = nil, locals = {}) #:nodoc: - return [super] unless layout_name && template.supports_streaming? + return [super.body] unless layout_name && template.supports_streaming? locals ||= {} layout = layout_name && find_layout(layout_name, locals.keys, [formats.first]) diff --git a/actionview/lib/action_view/renderer/template_renderer.rb b/actionview/lib/action_view/renderer/template_renderer.rb index c36baeffcd..83b990b081 100644 --- a/actionview/lib/action_view/renderer/template_renderer.rb +++ b/actionview/lib/action_view/renderer/template_renderer.rb @@ -8,9 +8,7 @@ module ActionView @details = extract_details(options) template = determine_template(options) - prepend_formats(template.formats) - - @lookup_context.rendered_format ||= (template.formats.first || formats.first) + prepend_formats(template.format) render_template(context, template, options[:layout], options[:locals] || {}) end @@ -31,7 +29,12 @@ module ActionView @lookup_context.with_fallbacks.find_file(options[:file], nil, false, keys, @details) elsif options.key?(:inline) handler = Template.handler_for_extension(options[:type] || "erb") - Template.new(options[:inline], "inline template", handler, locals: keys) + format = if handler.respond_to?(:default_format) + handler.default_format + else + @lookup_context.formats.first + end + Template::Inline.new(options[:inline], "inline template", handler, locals: keys, format: format) elsif options.key?(:template) if options[:template].respond_to?(:render) options[:template] @@ -46,23 +49,24 @@ module ActionView # Renders the given template. A string representing the layout can be # supplied as well. def render_template(view, template, layout_name, locals) - render_with_layout(view, layout_name, locals) do |layout| + render_with_layout(view, layout_name, template, locals) do |layout| instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do template.render(view, locals) { |*name| view._layout_for(*name) } end end end - def render_with_layout(view, path, locals) + def render_with_layout(view, path, template, locals) layout = path && find_layout(path, locals.keys, [formats.first]) content = yield(layout) - if layout + body = if layout view.view_flow.set(:layout, content) layout.render(view, locals) { |*name| view._layout_for(*name) } else content end + build_rendered_template(body, template, layout) end # This is the method which actually finds the layout using details in the lookup @@ -89,7 +93,7 @@ module ActionView raise unless template_exists?(layout, nil, false, [], all_details) end when Proc - resolve_layout(layout.call(formats), keys, formats) + resolve_layout(layout.call(@lookup_context, formats), keys, formats) else layout end diff --git a/actionview/lib/action_view/rendering.rb b/actionview/lib/action_view/rendering.rb index da92ce1f5e..ac861c44d4 100644 --- a/actionview/lib/action_view/rendering.rb +++ b/actionview/lib/action_view/rendering.rb @@ -26,6 +26,13 @@ module ActionView extend ActiveSupport::Concern include ActionView::ViewPaths + attr_reader :rendered_format + + def initialize + @rendered_format = nil + super + end + # Overwrite process to setup I18n proxy. def process(*) #:nodoc: old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context) @@ -82,7 +89,7 @@ module ActionView # # Override this method in a module to change the default behavior. def view_context - view_context_class.new(view_renderer, view_assigns, self) + view_context_class.new(lookup_context, view_assigns, self) end # Returns an object that is able to render templates. @@ -96,10 +103,6 @@ module ActionView _render_template(options) end - def rendered_format - Template::Types[lookup_context.rendered_format] - end - private # Find and render a template based on the options given. @@ -109,17 +112,22 @@ module ActionView context = view_context context.assign assigns if assigns - lookup_context.rendered_format = nil if options[:formats] lookup_context.variants = variant if variant - view_renderer.render(context, options) + rendered_template = context.in_rendering_context(options) do |renderer| + renderer.render_to_object(context, options) + end + + rendered_format = rendered_template.format || lookup_context.formats.first + @rendered_format = Template::Types[rendered_format] + + rendered_template.body end # Assign the rendered format to look up context. def _process_format(format) super lookup_context.formats = [format.to_sym] - lookup_context.rendered_format = lookup_context.formats.first end # Normalize args by converting render "foo" to render :action => "foo" and diff --git a/actionview/lib/action_view/template.rb b/actionview/lib/action_view/template.rb index 37f476e554..2c27e11b9e 100644 --- a/actionview/lib/action_view/template.rb +++ b/actionview/lib/action_view/template.rb @@ -115,28 +115,28 @@ module ActionView autoload :Error autoload :Handlers autoload :HTML + autoload :Inline autoload :Text autoload :Types end extend Template::Handlers - attr_accessor :locals, :formats, :variants, :virtual_path - attr_reader :source, :identifier, :handler, :original_encoding, :updated_at + attr_reader :variable, :format, :variant, :locals, :virtual_path - attr_reader :variable - - def initialize(source, identifier, handler, details) - format = details[:format] || (handler.default_format if handler.respond_to?(:default_format)) + def initialize(source, identifier, handler, format: nil, variant: nil, locals: nil, virtual_path: nil, updated_at: Time.now) + unless locals + ActiveSupport::Deprecation.warn "ActionView::Template#initialize requires a locals parameter" + locals = [] + end @source = source @identifier = identifier @handler = handler @compiled = false - @original_encoding = nil - @locals = details[:locals] || [] - @virtual_path = details[:virtual_path] + @locals = locals + @virtual_path = virtual_path @variable = if @virtual_path base = @virtual_path[-1] == "/" ? "" : File.basename(@virtual_path) @@ -144,12 +144,20 @@ module ActionView $1.to_sym end - @updated_at = details[:updated_at] || Time.now - @formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f } - @variants = [details[:variant]] + @updated_at = updated_at + @format = format + @variant = variant @compile_mutex = Mutex.new end + deprecate :original_encoding + deprecate def virtual_path=(_); end + deprecate def locals=(_); end + deprecate def formats=(_); end + deprecate def formats; Array(format); end + deprecate def variants=(_); end + deprecate def variants; [variant]; end + # Returns whether the underlying handler supports streaming. If so, # a streaming buffer *may* be passed when it starts rendering. def supports_streaming? @@ -165,14 +173,14 @@ module ActionView def render(view, locals, buffer = ActionView::OutputBuffer.new, &block) instrument_render_template do compile!(view) - view.run(method_name, locals, buffer, &block) + view.run(method_name, self, locals, buffer, &block) end rescue => e handle_render_error(view, e) end def type - @type ||= Types[@formats.first] if @formats.first + @type ||= Types[format] end # Receives a view object and return a template similar to self by using @virtual_path. @@ -194,8 +202,12 @@ module ActionView end end + def short_identifier + @short_identifier ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", "") : identifier + end + def inspect - @inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", "") : identifier + "#<#{self.class.name} #{short_identifier} locals=#{@locals.inspect}>" end # This method is responsible for properly setting the encoding of the @@ -249,11 +261,11 @@ module ActionView # to ensure that references to the template object can be marshalled as well. This means forgoing # the marshalling of the compiler mutex and instantiating that again on unmarshalling. def marshal_dump # :nodoc: - [ @source, @identifier, @handler, @compiled, @original_encoding, @locals, @virtual_path, @updated_at, @formats, @variants ] + [ @source, @identifier, @handler, @compiled, @locals, @virtual_path, @updated_at, @format, @variant ] end def marshal_load(array) # :nodoc: - @source, @identifier, @handler, @compiled, @original_encoding, @locals, @virtual_path, @updated_at, @formats, @variants = *array + @source, @identifier, @handler, @compiled, @locals, @virtual_path, @updated_at, @format, @variant = *array @compile_mutex = Mutex.new end @@ -369,7 +381,7 @@ module ActionView end def identifier_method_name - inspect.tr("^a-z_", "_") + short_identifier.tr("^a-z_", "_") end def instrument(action, &block) # :doc: diff --git a/actionview/lib/action_view/template/handlers/erb/erubi.rb b/actionview/lib/action_view/template/handlers/erb/erubi.rb index 15ca202024..247b6d75d1 100644 --- a/actionview/lib/action_view/template/handlers/erb/erubi.rb +++ b/actionview/lib/action_view/template/handlers/erb/erubi.rb @@ -26,8 +26,8 @@ module ActionView view = Class.new(ActionView::Base) { include action_view_erb_handler_context._routes.url_helpers class_eval("define_method(:_template) { |local_assigns, output_buffer| #{src} }", @filename || "(erubi)", 0) - }.with_context(action_view_erb_handler_context) - view.run(:_template, {}, ActionView::OutputBuffer.new) + }.empty + view.run(:_template, nil, {}, ActionView::OutputBuffer.new) end private diff --git a/actionview/lib/action_view/template/html.rb b/actionview/lib/action_view/template/html.rb index a262c6d9ad..ecd1c31e79 100644 --- a/actionview/lib/action_view/template/html.rb +++ b/actionview/lib/action_view/template/html.rb @@ -1,15 +1,21 @@ # frozen_string_literal: true +require "active_support/deprecation" + module ActionView #:nodoc: # = Action View HTML Template class Template #:nodoc: class HTML #:nodoc: - attr_accessor :type + attr_reader :type def initialize(string, type = nil) + unless type + ActiveSupport::Deprecation.warn "ActionView::Template::HTML#initialize requires a type parameter" + type = :html + end + @string = string.to_s - @type = Types[type] || type if type - @type ||= Types[:html] + @type = type end def identifier @@ -26,9 +32,12 @@ module ActionView #:nodoc: to_str end - def formats - [@type.respond_to?(:ref) ? @type.ref : @type.to_s] + def format + @type end + + def formats; Array(format); end + deprecate :formats end end end diff --git a/actionview/lib/action_view/template/inline.rb b/actionview/lib/action_view/template/inline.rb new file mode 100644 index 0000000000..44658487ea --- /dev/null +++ b/actionview/lib/action_view/template/inline.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +module ActionView #:nodoc: + class Template #:nodoc: + class Inline < Template #:nodoc: + # This finalizer is needed (and exactly with a proc inside another proc) + # otherwise templates leak in development. + Finalizer = proc do |method_name, mod| # :nodoc: + proc do + mod.module_eval do + remove_possible_method method_name + end + end + end + + def compile(mod) + super + ObjectSpace.define_finalizer(self, Finalizer[method_name, mod]) + end + end + end +end diff --git a/actionview/lib/action_view/template/resolver.rb b/actionview/lib/action_view/template/resolver.rb index 3b4594942b..1dc9c9919a 100644 --- a/actionview/lib/action_view/template/resolver.rb +++ b/actionview/lib/action_view/template/resolver.rb @@ -143,14 +143,18 @@ module ActionView # Normalizes the arguments and passes it on to find_templates. def find_all(name, prefix = nil, partial = false, details = {}, key = nil, locals = []) + locals = locals.map(&:to_s).sort!.freeze + cached(key, [name, prefix, partial], details, locals) do - find_templates(name, prefix, partial, details) + find_templates(name, prefix, partial, details, false, locals) end end def find_all_anywhere(name, prefix, partial = false, details = {}, key = nil, locals = []) + locals = locals.map(&:to_s).sort!.freeze + cached(key, [name, prefix, partial], details, locals) do - find_templates(name, prefix, partial, details, true) + find_templates(name, prefix, partial, details, true, locals) end end @@ -165,13 +169,8 @@ module ActionView # This is what child classes implement. No defaults are needed # because Resolver guarantees that the arguments are present and # normalized. - def find_templates(name, prefix, partial, details, outside_app_allowed = false) - raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details, outside_app_allowed = false) method" - end - - # Helpers that builds a path. Useful for building virtual paths. - def build_path(name, prefix, partial) - Path.build(name, prefix, partial) + def find_templates(name, prefix, partial, details, outside_app_allowed = false, locals = []) + raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details, outside_app_allowed = false, locals = []) method" end # Handles templates caching. If a key is given and caching is on @@ -180,25 +179,13 @@ module ActionView # resolver is fresher before returning it. def cached(key, path_info, details, locals) name, prefix, partial = path_info - locals = locals.map(&:to_s).sort! if key @cache.cache(key, name, prefix, partial, locals) do - decorate(yield, path_info, details, locals) + yield end else - decorate(yield, path_info, details, locals) - end - end - - # Ensures all the resolver information is set in the template. - def decorate(templates, path_info, details, locals) - cached = nil - templates.each do |t| - t.locals = locals - t.formats = details[:formats] || [:html] if t.formats.empty? - t.variants = details[:variants] || [] if t.variants.empty? - t.virtual_path ||= (cached ||= build_path(*path_info)) + yield end end end @@ -215,12 +202,12 @@ module ActionView private - def find_templates(name, prefix, partial, details, outside_app_allowed = false) + def find_templates(name, prefix, partial, details, outside_app_allowed = false, locals) path = Path.build(name, prefix, partial) - query(path, details, details[:formats], outside_app_allowed) + query(path, details, details[:formats], outside_app_allowed, locals) end - def query(path, details, formats, outside_app_allowed) + def query(path, details, formats, outside_app_allowed, locals) template_paths = find_template_paths_from_details(path, details) template_paths = reject_files_external_to_app(template_paths) unless outside_app_allowed @@ -231,6 +218,7 @@ module ActionView virtual_path: path.virtual, format: format, variant: variant, + locals: locals, updated_at: mtime(template) ) end @@ -300,8 +288,17 @@ module ActionView handler = Template.handler_for_extension(extension) format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last - format &&= Template::Types[format] + format = if format + Template::Types[format]&.ref + else + if handler.respond_to?(:default_format) # default_format can return nil + handler.default_format + else + nil + end + end + # Template::Types[format] and handler.default_format can return nil [handler, format, variant] end end @@ -422,9 +419,5 @@ module ActionView def self.instances [new(""), new("/")] end - - def decorate(*) - super.each { |t| t.virtual_path = nil } - end end end diff --git a/actionview/lib/action_view/template/text.rb b/actionview/lib/action_view/template/text.rb index f8d6c2811f..c5fd55f1b3 100644 --- a/actionview/lib/action_view/template/text.rb +++ b/actionview/lib/action_view/template/text.rb @@ -8,7 +8,6 @@ module ActionView #:nodoc: def initialize(string) @string = string.to_s - @type = Types[:text] end def identifier @@ -25,9 +24,12 @@ module ActionView #:nodoc: to_str end - def formats - [@type.ref] + def format + :text end + + def formats; Array(format); end + deprecate :formats end end end diff --git a/actionview/lib/action_view/testing/resolvers.rb b/actionview/lib/action_view/testing/resolvers.rb index d6203b95c5..3ca8420c6c 100644 --- a/actionview/lib/action_view/testing/resolvers.rb +++ b/actionview/lib/action_view/testing/resolvers.rb @@ -23,7 +23,7 @@ module ActionView #:nodoc: private - def query(path, exts, _, _) + def query(path, exts, _, _, locals) query = +"" EXTENSIONS.each_key do |ext| query << "(" << exts[ext].map { |e| e && Regexp.escape(".#{e}") }.join("|") << "|)" @@ -39,6 +39,7 @@ module ActionView #:nodoc: virtual_path: path.virtual, format: format, variant: variant, + locals: locals, updated_at: updated_at ) end @@ -48,9 +49,9 @@ module ActionView #:nodoc: end class NullResolver < PathResolver - def query(path, exts, _, _) + def query(path, exts, _, _, locals) handler, format, variant = extract_handler_and_format_and_variant(path) - [ActionView::Template.new("Template generated by Null Resolver", path.virtual, handler, virtual_path: path.virtual, format: format, variant: variant)] + [ActionView::Template.new("Template generated by Null Resolver", path.virtual, handler, virtual_path: path.virtual, format: format, variant: variant, locals: locals)] end end end diff --git a/actionview/package.json b/actionview/package.json index eb2a9f879e..98827efd62 100644 --- a/actionview/package.json +++ b/actionview/package.json @@ -1,6 +1,6 @@ { "name": "@rails/ujs", - "version": "6.0.0-beta1", + "version": "6.0.0-beta2", "description": "Ruby on Rails unobtrusive scripting adapter", "main": "lib/assets/compiled/rails-ujs.js", "files": [ diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb index b649b3c9dd..fe317bf39e 100644 --- a/actionview/test/abstract_unit.rb +++ b/actionview/test/abstract_unit.rb @@ -60,7 +60,7 @@ module RenderERBUtils string.strip, "test template", ActionView::Template.handler_for_extension(:erb), - {}) + format: :html, locals: []) view = ActionView::Base.with_empty_template_cache template.render(view.empty, {}).strip diff --git a/actionview/test/actionpack/controller/render_test.rb b/actionview/test/actionpack/controller/render_test.rb index 727d3fbc1a..52c3c54d96 100644 --- a/actionview/test/actionpack/controller/render_test.rb +++ b/actionview/test/actionpack/controller/render_test.rb @@ -174,6 +174,10 @@ class TestController < ActionController::Base render inline: "<%= controller_name %>" end + def inline_rendered_format_without_format + render inline: "test" + end + # :ported: def render_custom_code render plain: "hello world", status: 404 @@ -659,6 +663,7 @@ class RenderTest < ActionController::TestCase get :hello_world_from_rxml_using_action, to: "test#hello_world_from_rxml_using_action" get :hello_world_from_rxml_using_template, to: "test#hello_world_from_rxml_using_template" get :hello_world_with_layout_false, to: "test#hello_world_with_layout_false" + get :inline_rendered_format_without_format, to: "test#inline_rendered_format_without_format" get :layout_overriding_layout, to: "test#layout_overriding_layout" get :layout_test, to: "test#layout_test" get :layout_test_with_different_layout, to: "test#layout_test_with_different_layout" @@ -1015,6 +1020,12 @@ class RenderTest < ActionController::TestCase assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body end + def test_rendered_format_without_format + get :inline_rendered_format_without_format + assert_equal "test", @response.body + assert_equal "text/html", @response.content_type + end + def test_partials_list get :partials_list assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body diff --git a/actionview/test/actionpack/controller/view_paths_test.rb b/actionview/test/actionpack/controller/view_paths_test.rb index c5238dd746..4449d08496 100644 --- a/actionview/test/actionpack/controller/view_paths_test.rb +++ b/actionview/test/actionpack/controller/view_paths_test.rb @@ -143,8 +143,9 @@ class ViewLoadPathsTest < ActionController::TestCase "Decorated body", template.identifier, template.handler, - virtual_path: template.virtual_path, - format: template.formats + virtual_path: template.virtual_path, + format: template.format, + locals: template.locals ) end end diff --git a/actionview/test/activerecord/relation_cache_test.rb b/actionview/test/activerecord/relation_cache_test.rb index a6befc3ee5..6fe83dcb9a 100644 --- a/actionview/test/activerecord/relation_cache_test.rb +++ b/actionview/test/activerecord/relation_cache_test.rb @@ -11,13 +11,14 @@ class RelationCacheTest < ActionView::TestCase lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"]) @view_renderer = ActionView::Renderer.new(lookup_context) @virtual_path = "path" + @current_template = lookup_context.find "test/hello_world" controller.cache_store = ActiveSupport::Cache::MemoryStore.new end def test_cache_relation_other cache(Project.all) { concat("Hello World") } - assert_equal "Hello World", controller.cache_store.read("views/path/projects-#{Project.count}") + assert_equal "Hello World", controller.cache_store.read("views/test/hello_world:fa9482a68ce25bf7589b8eddad72f736/projects-#{Project.count}") end def view_cache_dependencies; []; end diff --git a/actionview/test/fixtures/test/_first.html.erb b/actionview/test/fixtures/test/_first.html.erb new file mode 100644 index 0000000000..2e2c825acb --- /dev/null +++ b/actionview/test/fixtures/test/_first.html.erb @@ -0,0 +1 @@ +"HTML" diff --git a/actionview/test/fixtures/test/_first.xml.erb b/actionview/test/fixtures/test/_first.xml.erb new file mode 100644 index 0000000000..9cf4f4ec85 --- /dev/null +++ b/actionview/test/fixtures/test/_first.xml.erb @@ -0,0 +1 @@ +"XML" diff --git a/actionview/test/fixtures/test/_first_layer.html.erb b/actionview/test/fixtures/test/_first_layer.html.erb new file mode 100644 index 0000000000..c1f1acb410 --- /dev/null +++ b/actionview/test/fixtures/test/_first_layer.html.erb @@ -0,0 +1,4 @@ +{"format":"HTML", "children": +[ + <%= render(partial: "first").chomp.html_safe %>, +]} diff --git a/actionview/test/fixtures/test/_first_layer.xml.erb b/actionview/test/fixtures/test/_first_layer.xml.erb new file mode 100644 index 0000000000..b8581bbbfc --- /dev/null +++ b/actionview/test/fixtures/test/_first_layer.xml.erb @@ -0,0 +1,4 @@ +{"format":"XML", "children": +[ + <%= render(partial: "first").chomp.html_safe %> +]} diff --git a/actionview/test/fixtures/test/_second.html.erb b/actionview/test/fixtures/test/_second.html.erb new file mode 100644 index 0000000000..2e2c825acb --- /dev/null +++ b/actionview/test/fixtures/test/_second.html.erb @@ -0,0 +1 @@ +"HTML" diff --git a/actionview/test/fixtures/test/_second.xml.erb b/actionview/test/fixtures/test/_second.xml.erb new file mode 100644 index 0000000000..9cf4f4ec85 --- /dev/null +++ b/actionview/test/fixtures/test/_second.xml.erb @@ -0,0 +1 @@ +"XML" diff --git a/actionview/test/fixtures/test/_second_layer.html.erb b/actionview/test/fixtures/test/_second_layer.html.erb new file mode 100644 index 0000000000..307706abd2 --- /dev/null +++ b/actionview/test/fixtures/test/_second_layer.html.erb @@ -0,0 +1,4 @@ +{"format":"HTML", "children": +[ + <%= render(partial: "first").chomp.html_safe %> +]} diff --git a/actionview/test/fixtures/test/_second_layer.xml.erb b/actionview/test/fixtures/test/_second_layer.xml.erb new file mode 100644 index 0000000000..b8581bbbfc --- /dev/null +++ b/actionview/test/fixtures/test/_second_layer.xml.erb @@ -0,0 +1,4 @@ +{"format":"XML", "children": +[ + <%= render(partial: "first").chomp.html_safe %> +]} diff --git a/actionview/test/fixtures/test/mixing_formats.html.erb b/actionview/test/fixtures/test/mixing_formats.html.erb new file mode 100644 index 0000000000..c65cdd7dd4 --- /dev/null +++ b/actionview/test/fixtures/test/mixing_formats.html.erb @@ -0,0 +1,5 @@ +{"format":"HTML", "children": +[ + <%= render(partial: "first", formats: :xml).chomp.html_safe %>, + <%= render(partial: "second").chomp.html_safe %> +]} diff --git a/actionview/test/fixtures/test/mixing_formats_deep.html.erb b/actionview/test/fixtures/test/mixing_formats_deep.html.erb new file mode 100644 index 0000000000..e328887eeb --- /dev/null +++ b/actionview/test/fixtures/test/mixing_formats_deep.html.erb @@ -0,0 +1,5 @@ +{"format":"HTML", "children": +[ + <%= render(partial: "first_layer", formats: :xml).chomp.html_safe %>, + <%= render(partial: "second_layer").chomp.html_safe %> +]} diff --git a/actionview/test/template/csp_helper_test.rb b/actionview/test/template/csp_helper_test.rb new file mode 100644 index 0000000000..1b7fd4665f --- /dev/null +++ b/actionview/test/template/csp_helper_test.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require "abstract_unit" + +class CspHelperWithCspEnabledTest < ActionView::TestCase + tests ActionView::Helpers::CspHelper + + def content_security_policy_nonce + "iyhD0Yc0W+c=" + end + + def content_security_policy? + true + end + + def test_csp_meta_tag + assert_equal "<meta name=\"csp-nonce\" content=\"iyhD0Yc0W+c=\" />", csp_meta_tag + end + + def test_csp_meta_tag_with_options + assert_equal "<meta property=\"csp-nonce\" name=\"csp-nonce\" content=\"iyhD0Yc0W+c=\" />", csp_meta_tag(property: "csp-nonce") + end +end + +class CspHelperWithCspDisabledTest < ActionView::TestCase + tests ActionView::Helpers::CspHelper + + def content_security_policy? + false + end + + def test_csp_meta_tag + assert_nil csp_meta_tag + end +end diff --git a/actionview/test/template/digestor_test.rb b/actionview/test/template/digestor_test.rb index ddaa7febb3..7affd3c005 100644 --- a/actionview/test/template/digestor_test.rb +++ b/actionview/test/template/digestor_test.rb @@ -7,9 +7,8 @@ require "action_view/dependency_tracker" class FixtureFinder < ActionView::LookupContext FIXTURES_DIR = File.expand_path("../fixtures/digestor", __dir__) - def initialize(details = {}) - super(ActionView::PathSet.new(["digestor", "digestor/api"]), details, []) - @rendered_format = :html + def self.build(details = {}) + new(ActionView::PathSet.new(["digestor", "digestor/api"]), details, []) end end @@ -146,13 +145,12 @@ class TemplateDigestorTest < ActionView::TestCase end def test_nested_template_deps_with_non_default_rendered_format - finder.rendered_format = nil nested_deps = [{ "comments/comments" => ["comments/comment"] }] assert_equal nested_deps, nested_dependencies("messages/thread") end def test_template_formats_of_nested_deps_with_non_default_rendered_format - finder.rendered_format = nil + @finder = finder.with_prepended_formats([:json]) assert_equal [:json], tree_template_formats("messages/thread").uniq end @@ -161,12 +159,10 @@ class TemplateDigestorTest < ActionView::TestCase end def test_template_dependencies_with_fallback_from_js_to_html_format - finder.rendered_format = :js assert_equal ["comments/comment"], dependencies("comments/show") end def test_template_digest_with_fallback_from_js_to_html_format - finder.rendered_format = :js assert_digest_difference("comments/show") do change_template("comments/_comment") end @@ -219,14 +215,14 @@ class TemplateDigestorTest < ActionView::TestCase def test_details_are_included_in_cache_key # Cache the template digest. - @finder = FixtureFinder.new(formats: [:html]) + @finder = FixtureFinder.build(formats: [:html]) old_digest = digest("events/_event") # Change the template; the cached digest remains unchanged. change_template("events/_event") # The details are changed, so a new cache key is generated. - @finder = FixtureFinder.new + @finder = FixtureFinder.build # The cache is busted. assert_not_equal old_digest, digest("events/_event") @@ -343,9 +339,14 @@ class TemplateDigestorTest < ActionView::TestCase finder_options = options.extract!(:variants, :format) finder.variants = finder_options[:variants] || [] - finder.rendered_format = finder_options[:format] if finder_options[:format] - ActionView::Digestor.digest(name: template_name, finder: finder, dependencies: (options[:dependencies] || [])) + finder_with_formats = if finder_options[:format] + finder.with_prepended_formats(Array(finder_options[:format])) + else + finder + end + + ActionView::Digestor.digest(name: template_name, format: finder_options[:format], finder: finder_with_formats, dependencies: (options[:dependencies] || [])) end def dependencies(template_name) @@ -360,7 +361,7 @@ class TemplateDigestorTest < ActionView::TestCase def tree_template_formats(template_name) tree = ActionView::Digestor.tree(template_name, finder) - tree.flatten.map(&:template).compact.flat_map(&:formats) + tree.flatten.map(&:template).compact.map(&:format) end def disable_resolver_caching @@ -371,7 +372,7 @@ class TemplateDigestorTest < ActionView::TestCase end def finder - @finder ||= FixtureFinder.new + @finder ||= FixtureFinder.build end def change_template(template_name, variant = nil) diff --git a/actionview/test/template/form_helper/form_with_test.rb b/actionview/test/template/form_helper/form_with_test.rb index f84c9b2b73..42069340f1 100644 --- a/actionview/test/template/form_helper/form_with_test.rb +++ b/actionview/test/template/form_helper/form_with_test.rb @@ -994,7 +994,7 @@ class FormWithActsLikeFormForTest < FormWithTest end def test_submit_with_object_as_new_record_and_locale_strings - with_locale :submit do + I18n.with_locale :submit do @post.persisted = false @post.stub(:to_key, nil) do form_with(model: @post) do |f| @@ -1011,7 +1011,7 @@ class FormWithActsLikeFormForTest < FormWithTest end def test_submit_with_object_as_existing_record_and_locale_strings - with_locale :submit do + I18n.with_locale :submit do form_with(model: @post) do |f| concat f.submit end @@ -1025,7 +1025,7 @@ class FormWithActsLikeFormForTest < FormWithTest end def test_submit_without_object_and_locale_strings - with_locale :submit do + I18n.with_locale :submit do form_with(scope: :post) do |f| concat f.submit class: "extra" end @@ -1039,7 +1039,7 @@ class FormWithActsLikeFormForTest < FormWithTest end def test_submit_with_object_which_is_overwritten_by_scope_option - with_locale :submit do + I18n.with_locale :submit do form_with(model: @post, scope: :another_post) do |f| concat f.submit end @@ -1054,7 +1054,7 @@ class FormWithActsLikeFormForTest < FormWithTest def test_submit_with_object_which_is_namespaced blog_post = Blog::Post.new("And his name will be forty and four.", 44) - with_locale :submit do + I18n.with_locale :submit do form_with(model: blog_post) do |f| concat f.submit end @@ -2357,11 +2357,4 @@ class FormWithActsLikeFormForTest < FormWithTest def protect_against_forgery? false end - - def with_locale(testing_locale = :label) - old_locale, I18n.locale = I18n.locale, testing_locale - yield - ensure - I18n.locale = old_locale - end end diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb index 5972946074..91052e5ae2 100644 --- a/actionview/test/template/form_helper_test.rb +++ b/actionview/test/template/form_helper_test.rb @@ -203,31 +203,31 @@ class FormHelperTest < ActionView::TestCase end def test_label_with_locales_strings - with_locale :label do + I18n.with_locale :label do assert_dom_equal('<label for="post_body">Write entire text here</label>', label("post", "body")) end end def test_label_with_human_attribute_name - with_locale :label do + I18n.with_locale :label do assert_dom_equal('<label for="post_cost">Total cost</label>', label(:post, :cost)) end end def test_label_with_human_attribute_name_and_options - with_locale :label do + I18n.with_locale :label do assert_dom_equal('<label for="post_language_spanish">Espanol</label>', label(:post, :language, value: "spanish")) end end def test_label_with_locales_symbols - with_locale :label do + I18n.with_locale :label do assert_dom_equal('<label for="post_body">Write entire text here</label>', label(:post, :body)) end end def test_label_with_locales_and_options - with_locale :label do + I18n.with_locale :label do assert_dom_equal( '<label for="post_body" class="post_body">Write entire text here</label>', label(:post, :body, class: "post_body") @@ -236,13 +236,13 @@ class FormHelperTest < ActionView::TestCase end def test_label_with_locales_and_value - with_locale :label do + I18n.with_locale :label do assert_dom_equal('<label for="post_color_red">Rojo</label>', label(:post, :color, value: "red")) end end def test_label_with_locales_and_nested_attributes - with_locale :label do + I18n.with_locale :label do form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:comments) do |cf| concat cf.label(:body) @@ -258,7 +258,7 @@ class FormHelperTest < ActionView::TestCase end def test_label_with_locales_fallback_and_nested_attributes - with_locale :label do + I18n.with_locale :label do form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:tags) do |cf| concat cf.label(:value) @@ -358,7 +358,7 @@ class FormHelperTest < ActionView::TestCase end def test_label_with_block_and_builder - with_locale :label do + I18n.with_locale :label do assert_dom_equal( '<label for="post_body"><b>Write entire text here</b></label>', label(:post, :body) { |b| raw("<b>#{b.translation}</b>") } @@ -381,7 +381,7 @@ class FormHelperTest < ActionView::TestCase end def test_label_with_to_model_and_overridden_model_name - with_locale :label do + I18n.with_locale :label do assert_dom_equal( %{<label for="post_delegator_title">Delegate model_name title</label>}, label(:post_delegator, :title) @@ -390,19 +390,19 @@ class FormHelperTest < ActionView::TestCase end def test_text_field_placeholder_without_locales - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal('<input id="post_body" name="post[body]" placeholder="Body" type="text" value="Back to the hill and over it again!" />', text_field(:post, :body, placeholder: true)) end end def test_text_field_placeholder_with_locales - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal('<input id="post_title" name="post[title]" placeholder="What is this about?" type="text" value="Hello World" />', text_field(:post, :title, placeholder: true)) end end def test_text_field_placeholder_with_locales_and_to_model - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal( '<input id="post_delegator_title" name="post_delegator[title]" placeholder="Delegate model_name title" type="text" value="Hello World" />', text_field(:post_delegator, :title, placeholder: true) @@ -411,7 +411,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_field_placeholder_with_human_attribute_name - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal('<input id="post_cost" name="post[cost]" placeholder="Total cost" type="text" />', text_field(:post, :cost, placeholder: true)) end end @@ -424,25 +424,25 @@ class FormHelperTest < ActionView::TestCase end def test_text_field_placeholder_with_string_value - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal('<input id="post_cost" name="post[cost]" placeholder="HOW MUCH?" type="text" />', text_field(:post, :cost, placeholder: "HOW MUCH?")) end end def test_text_field_placeholder_with_human_attribute_name_and_value - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal('<input id="post_cost" name="post[cost]" placeholder="Pounds" type="text" />', text_field(:post, :cost, placeholder: :uk)) end end def test_text_field_placeholder_with_locales_and_value - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal('<input id="post_written_on" name="post[written_on]" placeholder="Escrito en" type="text" value="2004-06-15" />', text_field(:post, :written_on, placeholder: :spanish)) end end def test_text_field_placeholder_with_locales_and_nested_attributes - with_locale :placeholder do + I18n.with_locale :placeholder do form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:comments) do |cf| concat cf.text_field(:body, placeholder: true) @@ -458,7 +458,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_field_placeholder_with_locales_fallback_and_nested_attributes - with_locale :placeholder do + I18n.with_locale :placeholder do form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:tags) do |cf| concat cf.text_field(:value, placeholder: true) @@ -861,7 +861,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_area_placeholder_without_locales - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal( %{<textarea id="post_body" name="post[body]" placeholder="Body">\nBack to the hill and over it again!</textarea>}, text_area(:post, :body, placeholder: true) @@ -870,7 +870,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_area_placeholder_with_locales - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal( %{<textarea id="post_title" name="post[title]" placeholder="What is this about?">\nHello World</textarea>}, text_area(:post, :title, placeholder: true) @@ -879,7 +879,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_area_placeholder_with_human_attribute_name - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal( %{<textarea id="post_cost" name="post[cost]" placeholder="Total cost">\n</textarea>}, text_area(:post, :cost, placeholder: true) @@ -888,7 +888,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_area_placeholder_with_string_value - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal( %{<textarea id="post_cost" name="post[cost]" placeholder="HOW MUCH?">\n</textarea>}, text_area(:post, :cost, placeholder: "HOW MUCH?") @@ -897,7 +897,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_area_placeholder_with_human_attribute_name_and_value - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal( %{<textarea id="post_cost" name="post[cost]" placeholder="Pounds">\n</textarea>}, text_area(:post, :cost, placeholder: :uk) @@ -906,7 +906,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_area_placeholder_with_locales_and_value - with_locale :placeholder do + I18n.with_locale :placeholder do assert_dom_equal( %{<textarea id="post_written_on" name="post[written_on]" placeholder="Escrito en">\n2004-06-15</textarea>}, text_area(:post, :written_on, placeholder: :spanish) @@ -915,7 +915,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_area_placeholder_with_locales_and_nested_attributes - with_locale :placeholder do + I18n.with_locale :placeholder do form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:comments) do |cf| concat cf.text_area(:body, placeholder: true) @@ -931,7 +931,7 @@ class FormHelperTest < ActionView::TestCase end def test_text_area_placeholder_with_locales_fallback_and_nested_attributes - with_locale :placeholder do + I18n.with_locale :placeholder do form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:tags) do |cf| concat cf.text_area(:value, placeholder: true) @@ -2260,7 +2260,7 @@ class FormHelperTest < ActionView::TestCase end def test_submit_with_object_as_new_record_and_locale_strings - with_locale :submit do + I18n.with_locale :submit do @post.persisted = false @post.stub(:to_key, nil) do form_for(@post) do |f| @@ -2277,7 +2277,7 @@ class FormHelperTest < ActionView::TestCase end def test_submit_with_object_as_existing_record_and_locale_strings - with_locale :submit do + I18n.with_locale :submit do form_for(@post) do |f| concat f.submit end @@ -2291,7 +2291,7 @@ class FormHelperTest < ActionView::TestCase end def test_submit_without_object_and_locale_strings - with_locale :submit do + I18n.with_locale :submit do form_for(:post) do |f| concat f.submit class: "extra" end @@ -2305,7 +2305,7 @@ class FormHelperTest < ActionView::TestCase end def test_submit_with_object_which_is_overwritten_by_as_option - with_locale :submit do + I18n.with_locale :submit do form_for(@post, as: :another_post) do |f| concat f.submit end @@ -2320,7 +2320,7 @@ class FormHelperTest < ActionView::TestCase def test_submit_with_object_which_is_namespaced blog_post = Blog::Post.new("And his name will be forty and four.", 44) - with_locale :submit do + I18n.with_locale :submit do form_for(blog_post) do |f| concat f.submit end @@ -3554,7 +3554,6 @@ class FormHelperTest < ActionView::TestCase end private - def hidden_fields(options = {}) method = options[:method] @@ -3593,13 +3592,6 @@ class FormHelperTest < ActionView::TestCase false end - def with_locale(testing_locale = :label) - old_locale, I18n.locale = I18n.locale, testing_locale - yield - ensure - I18n.locale = old_locale - end - def with_default_enforce_utf8(value) old_value = ActionView::Helpers::FormTagHelper.default_enforce_utf8 ActionView::Helpers::FormTagHelper.default_enforce_utf8 = value diff --git a/actionview/test/template/html_test.rb b/actionview/test/template/html_test.rb index 5cdff74d60..c5fc8f906c 100644 --- a/actionview/test/template/html_test.rb +++ b/actionview/test/template/html_test.rb @@ -4,16 +4,16 @@ require "abstract_unit" class HTMLTest < ActiveSupport::TestCase test "formats returns symbol for recognized MIME type" do - assert_equal [:html], ActionView::Template::HTML.new("", :html).formats + assert_equal :html, ActionView::Template::HTML.new("", :html).format end test "formats returns string for recognized MIME type when MIME does not have symbol" do foo = Mime::Type.lookup("foo") assert_nil foo.to_sym - assert_equal ["foo"], ActionView::Template::HTML.new("", foo).formats + assert_equal "foo", ActionView::Template::HTML.new("", foo).format end test "formats returns string for unknown MIME type" do - assert_equal ["foo"], ActionView::Template::HTML.new("", "foo").formats + assert_equal "foo", ActionView::Template::HTML.new("", "foo").format end end diff --git a/actionview/test/template/log_subscriber_test.rb b/actionview/test/template/log_subscriber_test.rb index 83bb651ea3..85735139c1 100644 --- a/actionview/test/template/log_subscriber_test.rb +++ b/actionview/test/template/log_subscriber_test.rb @@ -16,8 +16,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase view_paths = ActionController::Base.view_paths lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"]) - renderer = ActionView::Renderer.new(lookup_context) - @view = ActionView::Base.with_empty_template_cache.new(renderer, {}) + @view = ActionView::Base.with_empty_template_cache.new(lookup_context, {}) ActionView::LogSubscriber.attach_to :action_view diff --git a/actionview/test/template/lookup_context_test.rb b/actionview/test/template/lookup_context_test.rb index 290f832794..62935620e9 100644 --- a/actionview/test/template/lookup_context_test.rb +++ b/actionview/test/template/lookup_context_test.rb @@ -17,6 +17,16 @@ class LookupContextTest < ActiveSupport::TestCase I18n.locale = :en end + test "rendered_format is deprecated" do + assert_deprecated do + @lookup_context.rendered_format = "foo" + end + + assert_deprecated do + assert_equal "foo", @lookup_context.rendered_format + end + end + test "allows to override default_formats with ActionView::Base.default_formats" do formats = ActionView::Base.default_formats ActionView::Base.default_formats = [:foo, :bar] @@ -111,11 +121,11 @@ class LookupContextTest < ActiveSupport::TestCase assert_equal "Hello texty phone!", template.source end - test "found templates respects given formats if one cannot be found from template or handler" do + test "found templates have nil format if one cannot be found from template or handler" do assert_called(ActionView::Template::Handlers::Builder, :default_format, returns: nil) do @lookup_context.formats = [:text] template = @lookup_context.find("hello", %w(test)) - assert_equal [:text], template.formats + assert_nil template.format end end diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb index 3f298d81f3..1f6dbfc4a5 100644 --- a/actionview/test/template/render_test.rb +++ b/actionview/test/template/render_test.rb @@ -20,7 +20,10 @@ module RenderTestCases controller = TestController.new - @controller_view = controller.view_context_class.with_empty_template_cache.new(controller.view_renderer, controller.view_assigns, controller) + @controller_view = controller.view_context_class.with_empty_template_cache.new( + controller.lookup_context, + controller.view_assigns, + controller) # Reload and register danish language for testing I18n.backend.store_translations "da", {} @@ -30,6 +33,21 @@ module RenderTestCases assert_equal ORIGINAL_LOCALES, I18n.available_locales.map(&:to_s).sort end + def test_implicit_format_comes_from_parent_template + rendered_templates = JSON.parse(@controller_view.render(template: "test/mixing_formats")) + assert_equal({ "format" => "HTML", + "children" => ["XML", "HTML"] }, rendered_templates) + end + + def test_implicit_format_comes_from_parent_template_cascading + rendered_templates = JSON.parse(@controller_view.render(template: "test/mixing_formats_deep")) + assert_equal({ "format" => "HTML", + "children" => [ + { "format" => "XML", "children" => ["XML"] }, + { "format" => "HTML", "children" => ["HTML"] }, + ] }, rendered_templates) + end + def test_render_without_options e = assert_raises(ArgumentError) { @view.render() } assert_match(/You invoked render but did not give any of (.+) option\./, e.message) @@ -51,11 +69,6 @@ module RenderTestCases assert_match "<error>No Comment</error>", @view.render(template: "comments/empty", formats: [:xml]) end - def test_rendered_format_without_format - @view.render(inline: "test") - assert_equal :html, @view.lookup_context.rendered_format - end - def test_render_partial_implicitly_use_format_of_the_rendered_template @view.lookup_context.formats = [:json] assert_equal "Hello world", @view.render(template: "test/one", formats: [:html]) @@ -68,7 +81,7 @@ module RenderTestCases def test_render_partial_use_last_prepended_format_for_partials_with_the_same_names @view.lookup_context.formats = [:html] - assert_equal "\nHTML Template, but JSON partial", @view.render(template: "test/change_priority") + assert_equal "\nHTML Template, but HTML partial", @view.render(template: "test/change_priority") end def test_render_template_with_a_missing_partial_of_another_format @@ -347,6 +360,17 @@ module RenderTestCases assert_deprecated do ActionView::Base.new ["/a"] end + + assert_deprecated do + ActionView::Base.new ActionView::PathSet.new ["/a"] + end + end + + def test_without_compiled_method_container_is_deprecated + view = ActionView::Base.with_view_paths(ActionController::Base.view_paths) + assert_deprecated("ActionView::Base instances must implement `compiled_method_container`") do + assert_equal "Hello world!", view.render(file: "test/hello_world") + end end def test_render_partial_without_object_does_not_put_partial_name_to_local_assigns @@ -718,10 +742,17 @@ class CachedCollectionViewRenderTest < ActiveSupport::TestCase end teardown do - GC.start I18n.reload! end + test "template body written to cache" do + customer = Customer.new("david", 1) + key = cache_key(customer, "test/_customer") + assert_nil ActionView::PartialRenderer.collection_cache.read(key) + @view.render(partial: "test/customer", collection: [customer], cached: true) + assert_equal "Hello: david", ActionView::PartialRenderer.collection_cache.read(key) + end + test "collection caching does not cache by default" do customer = Customer.new("david", 1) key = cache_key(customer, "test/_customer") @@ -752,9 +783,20 @@ class CachedCollectionViewRenderTest < ActiveSupport::TestCase @view.render(partial: "test/cached_customer", collection: [customer], cached: true) end + test "collection caching does not work on multi-partials" do + a = Object.new + b = Object.new + def a.to_partial_path; "test/partial_iteration_1"; end + def b.to_partial_path; "test/partial_iteration_2"; end + + assert_raises(NotImplementedError) do + @controller_view.render(partial: [a, b], cached: true) + end + end + private def cache_key(*names, virtual_path) - digest = ActionView::Digestor.digest name: virtual_path, finder: @view.lookup_context, dependencies: [] + digest = ActionView::Digestor.digest name: virtual_path, format: :html, finder: @view.lookup_context, dependencies: [] @view.combined_fragment_cache_key([ "#{virtual_path}:#{digest}", *names ]) end end diff --git a/actionview/test/template/resolver_patterns_test.rb b/actionview/test/template/resolver_patterns_test.rb index 1e1a4c5063..8122de779f 100644 --- a/actionview/test/template/resolver_patterns_test.rb +++ b/actionview/test/template/resolver_patterns_test.rb @@ -19,7 +19,7 @@ class ResolverPatternsTest < ActiveSupport::TestCase assert_equal 1, templates.size, "expected one template" assert_equal "Hello custom patterns!", templates.first.source assert_equal "custom_pattern/path", templates.first.virtual_path - assert_equal [:html], templates.first.formats + assert_nil templates.first.format end def test_should_return_all_templates_when_ambiguous_pattern diff --git a/actionview/test/template/template_test.rb b/actionview/test/template/template_test.rb index a069c8f2d0..71fb99115b 100644 --- a/actionview/test/template/template_test.rb +++ b/actionview/test/template/template_test.rb @@ -38,7 +38,9 @@ class TestERBTemplate < ActiveSupport::TestCase "<%= @virtual_path %>", "partial", ERBHandler, - virtual_path: "partial" + virtual_path: "partial", + format: :html, + locals: [] ) end @@ -55,8 +57,9 @@ class TestERBTemplate < ActiveSupport::TestCase end end - def new_template(body = "<%= hello %>", details = { format: :html }) - ActionView::Template.new(body.dup, "hello template", details.fetch(:handler) { ERBHandler }, { virtual_path: "hello" }.merge!(details)) + def new_template(body = "<%= hello %>", details = {}) + details = { format: :html, locals: [] }.merge details + ActionView::Template.new(body.dup, "hello template", details.delete(:handler) || ERBHandler, { virtual_path: "hello" }.merge!(details)) end def render(locals = {}) @@ -101,8 +104,7 @@ class TestERBTemplate < ActiveSupport::TestCase end def test_locals - @template = new_template("<%= my_local %>") - @template.locals = [:my_local] + @template = new_template("<%= my_local %>", locals: [:my_local]) assert_equal "I am a local", render(my_local: "I am a local") end @@ -120,16 +122,14 @@ class TestERBTemplate < ActiveSupport::TestCase end def test_refresh_with_templates - @template = new_template("Hello", virtual_path: "test/foo/bar") - @template.locals = [:key] + @template = new_template("Hello", virtual_path: "test/foo/bar", locals: [:key]) assert_called_with(@context.lookup_context, :find_template, ["bar", %w(test/foo), false, [:key]], returns: "template") do assert_equal "template", @template.refresh(@context) end end def test_refresh_with_partials - @template = new_template("Hello", virtual_path: "test/_foo") - @template.locals = [:key] + @template = new_template("Hello", virtual_path: "test/_foo", locals: [:key]) assert_called_with(@context.lookup_context, :find_template, ["foo", %w(test), true, [:key]], returns: "partial") do assert_equal "partial", @template.refresh(@context) end @@ -213,4 +213,14 @@ class TestERBTemplate < ActiveSupport::TestCase ensure silence_warnings { Encoding.default_external = old } end + + def test_short_identifier + @template = new_template("hello") + assert_equal "hello template", @template.short_identifier + end + + def test_template_inspect + @template = new_template("hello") + assert_equal "#<ActionView::Template hello template locals=[]>", @template.inspect + end end diff --git a/actionview/test/template/testing/fixture_resolver_test.rb b/actionview/test/template/testing/fixture_resolver_test.rb index 9954e3500d..afb6686dac 100644 --- a/actionview/test/template/testing/fixture_resolver_test.rb +++ b/actionview/test/template/testing/fixture_resolver_test.rb @@ -15,6 +15,6 @@ class FixtureResolverTest < ActiveSupport::TestCase assert_equal 1, templates.size, "expected one template" assert_equal "this text", templates.first.source assert_equal "arbitrary/path", templates.first.virtual_path - assert_equal [:html], templates.first.formats + assert_nil templates.first.format end end diff --git a/actionview/test/template/testing/null_resolver_test.rb b/actionview/test/template/testing/null_resolver_test.rb index 53364c1d90..c7c78804c0 100644 --- a/actionview/test/template/testing/null_resolver_test.rb +++ b/actionview/test/template/testing/null_resolver_test.rb @@ -9,6 +9,6 @@ class NullResolverTest < ActiveSupport::TestCase assert_equal 1, templates.size, "expected one template" assert_equal "Template generated by Null Resolver", templates.first.source assert_equal "arbitrary/path.erb", templates.first.virtual_path.to_s - assert_equal [:html], templates.first.formats + assert_nil templates.first.format end end diff --git a/actionview/test/template/text_test.rb b/actionview/test/template/text_test.rb index 0c6470df21..c837c53587 100644 --- a/actionview/test/template/text_test.rb +++ b/actionview/test/template/text_test.rb @@ -3,8 +3,8 @@ require "abstract_unit" class TextTest < ActiveSupport::TestCase - test "formats always return :text" do - assert_equal [:text], ActionView::Template::Text.new("").formats + test "format always return :text" do + assert_equal :text, ActionView::Template::Text.new("").format end test "identifier should return 'text template'" do |