From 80e66cc4d90bf8c15d1a5f6e3152e90147f00772 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 6 Aug 2016 19:55:02 +0200 Subject: normalizes indentation and whitespace across the project --- actionview/lib/action_view/flows.rb | 6 +- .../lib/action_view/helpers/active_model_helper.rb | 12 +- actionview/lib/action_view/helpers/csrf_helper.rb | 2 +- actionview/lib/action_view/helpers/form_helper.rb | 4 +- .../lib/action_view/helpers/number_helper.rb | 76 ++--- actionview/lib/action_view/helpers/tags/base.rb | 198 ++++++------- .../lib/action_view/helpers/tags/check_box.rb | 32 +- .../helpers/tags/collection_check_boxes.rb | 12 +- .../action_view/helpers/tags/collection_helpers.rb | 114 ++++---- .../lib/action_view/helpers/tags/date_select.rb | 68 ++--- .../lib/action_view/helpers/tags/radio_button.rb | 6 +- actionview/lib/action_view/helpers/tags/select.rb | 6 +- .../lib/action_view/helpers/tags/text_field.rb | 6 +- .../lib/action_view/helpers/tags/translator.rb | 24 +- actionview/lib/action_view/helpers/text_helper.rb | 18 +- actionview/lib/action_view/layouts.rb | 26 +- actionview/lib/action_view/path_set.rb | 38 +-- .../lib/action_view/renderer/abstract_renderer.rb | 30 +- .../lib/action_view/renderer/partial_renderer.rb | 324 ++++++++++----------- .../renderer/streaming_template_renderer.rb | 88 +++--- .../lib/action_view/renderer/template_renderer.rb | 118 ++++---- .../lib/action_view/template/handlers/builder.rb | 10 +- actionview/lib/action_view/template/resolver.rb | 148 +++++----- actionview/lib/action_view/view_paths.rb | 6 +- 24 files changed, 686 insertions(+), 686 deletions(-) (limited to 'actionview/lib/action_view') diff --git a/actionview/lib/action_view/flows.rb b/actionview/lib/action_view/flows.rb index 73ebf8dd55..ed30afb83d 100644 --- a/actionview/lib/action_view/flows.rb +++ b/actionview/lib/action_view/flows.rb @@ -68,8 +68,8 @@ module ActionView private - def inside_fiber? - Fiber.current.object_id != @root - end + def inside_fiber? + Fiber.current.object_id != @root + end end end diff --git a/actionview/lib/action_view/helpers/active_model_helper.rb b/actionview/lib/action_view/helpers/active_model_helper.rb index 4f76195760..4bb5788a16 100644 --- a/actionview/lib/action_view/helpers/active_model_helper.rb +++ b/actionview/lib/action_view/helpers/active_model_helper.rb @@ -37,13 +37,13 @@ module ActionView private - def object_has_errors? - object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present? - end + def object_has_errors? + object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present? + end - def tag_generate_errors?(options) - options["type"] != "hidden" - end + def tag_generate_errors?(options) + options["type"] != "hidden" + end end end end diff --git a/actionview/lib/action_view/helpers/csrf_helper.rb b/actionview/lib/action_view/helpers/csrf_helper.rb index d07115a5ee..2a15d2aa5a 100644 --- a/actionview/lib/action_view/helpers/csrf_helper.rb +++ b/actionview/lib/action_view/helpers/csrf_helper.rb @@ -14,7 +14,7 @@ module ActionView # # You don't need to use these tags for regular forms as they generate their own hidden fields. # - # For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the + # For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the # "X-CSRF-Token" HTTP header. If you are using jQuery with jquery-rails this happens automatically. # def csrf_meta_tags diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb index 3f7b6c0f9c..f470375988 100644 --- a/actionview/lib/action_view/helpers/form_helper.rb +++ b/actionview/lib/action_view/helpers/form_helper.rb @@ -467,7 +467,7 @@ module ActionView ) options[:url] ||= if options.key?(:format) - polymorphic_path(record, format: options.delete(:format)) + polymorphic_path(record, format: options.delete(:format)) else polymorphic_path(record, {}) end @@ -1573,7 +1573,7 @@ module ActionView end record_name = if index - "#{object_name}[#{index}][#{record_name}]" + "#{object_name}[#{index}][#{record_name}]" elsif record_name.to_s.end_with?("[]") record_name = record_name.to_s.sub(/(.*)\[\]$/, "[\\1][#{record_object.id}]") "#{object_name}#{record_name}" diff --git a/actionview/lib/action_view/helpers/number_helper.rb b/actionview/lib/action_view/helpers/number_helper.rb index 3f665b39a3..9540850004 100644 --- a/actionview/lib/action_view/helpers/number_helper.rb +++ b/actionview/lib/action_view/helpers/number_helper.rb @@ -393,53 +393,53 @@ module ActionView private - def delegate_number_helper_method(method, number, options) - return unless number - options = escape_unsafe_options(options.symbolize_keys) + def delegate_number_helper_method(method, number, options) + return unless number + options = escape_unsafe_options(options.symbolize_keys) - wrap_with_output_safety_handling(number, options.delete(:raise)) { - ActiveSupport::NumberHelper.public_send(method, number, options) - } - end + wrap_with_output_safety_handling(number, options.delete(:raise)) { + ActiveSupport::NumberHelper.public_send(method, number, options) + } + end - def escape_unsafe_options(options) - options[:format] = ERB::Util.html_escape(options[:format]) if options[:format] - options[:negative_format] = ERB::Util.html_escape(options[:negative_format]) if options[:negative_format] - options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator] - options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter] - options[:unit] = ERB::Util.html_escape(options[:unit]) if options[:unit] && !options[:unit].html_safe? - options[:units] = escape_units(options[:units]) if options[:units] && Hash === options[:units] - options - end + def escape_unsafe_options(options) + options[:format] = ERB::Util.html_escape(options[:format]) if options[:format] + options[:negative_format] = ERB::Util.html_escape(options[:negative_format]) if options[:negative_format] + options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator] + options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter] + options[:unit] = ERB::Util.html_escape(options[:unit]) if options[:unit] && !options[:unit].html_safe? + options[:units] = escape_units(options[:units]) if options[:units] && Hash === options[:units] + options + end - def escape_units(units) - Hash[units.map do |k, v| - [k, ERB::Util.html_escape(v)] - end] - end + def escape_units(units) + Hash[units.map do |k, v| + [k, ERB::Util.html_escape(v)] + end] + end - def wrap_with_output_safety_handling(number, raise_on_invalid, &block) - valid_float = valid_float?(number) - raise InvalidNumberError, number if raise_on_invalid && !valid_float + def wrap_with_output_safety_handling(number, raise_on_invalid, &block) + valid_float = valid_float?(number) + raise InvalidNumberError, number if raise_on_invalid && !valid_float - formatted_number = yield + formatted_number = yield - if valid_float || number.html_safe? - formatted_number.html_safe - else - formatted_number + if valid_float || number.html_safe? + formatted_number.html_safe + else + formatted_number + end end - end - def valid_float?(number) - !parse_float(number, false).nil? - end + def valid_float?(number) + !parse_float(number, false).nil? + end - def parse_float(number, raise_error) - Float(number) - rescue ArgumentError, TypeError - raise InvalidNumberError, number if raise_error - end + def parse_float(number, raise_error) + Float(number) + rescue ArgumentError, TypeError + raise InvalidNumberError, number if raise_error + end end end end diff --git a/actionview/lib/action_view/helpers/tags/base.rb b/actionview/lib/action_view/helpers/tags/base.rb index a86600aeb9..43335023ce 100644 --- a/actionview/lib/action_view/helpers/tags/base.rb +++ b/actionview/lib/action_view/helpers/tags/base.rb @@ -24,136 +24,136 @@ module ActionView private - def value(object) - object.public_send @method_name if object - end + def value(object) + object.public_send @method_name if object + end - def value_before_type_cast(object) - unless object.nil? - method_before_type_cast = @method_name + "_before_type_cast" + def value_before_type_cast(object) + unless object.nil? + method_before_type_cast = @method_name + "_before_type_cast" - if value_came_from_user?(object) && object.respond_to?(method_before_type_cast) - object.public_send(method_before_type_cast) - else - value(object) + if value_came_from_user?(object) && object.respond_to?(method_before_type_cast) + object.public_send(method_before_type_cast) + else + value(object) + end end end - end - def value_came_from_user?(object) - method_name = "#{@method_name}_came_from_user?" - !object.respond_to?(method_name) || object.public_send(method_name) - end + def value_came_from_user?(object) + method_name = "#{@method_name}_came_from_user?" + !object.respond_to?(method_name) || object.public_send(method_name) + end - def retrieve_object(object) - if object - object - elsif @template_object.instance_variable_defined?("@#{@object_name}") - @template_object.instance_variable_get("@#{@object_name}") + def retrieve_object(object) + if object + object + elsif @template_object.instance_variable_defined?("@#{@object_name}") + @template_object.instance_variable_get("@#{@object_name}") + end + rescue NameError + # As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil. + nil end - rescue NameError - # As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil. - nil - end - def retrieve_autoindex(pre_match) - object = self.object || @template_object.instance_variable_get("@#{pre_match}") - if object && object.respond_to?(:to_param) - object.to_param - else - raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}" + def retrieve_autoindex(pre_match) + object = self.object || @template_object.instance_variable_get("@#{pre_match}") + if object && object.respond_to?(:to_param) + object.to_param + else + raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}" + end end - end - def add_default_name_and_id_for_value(tag_value, options) - if tag_value.nil? - add_default_name_and_id(options) - else - specified_id = options["id"] - add_default_name_and_id(options) + def add_default_name_and_id_for_value(tag_value, options) + if tag_value.nil? + add_default_name_and_id(options) + else + specified_id = options["id"] + add_default_name_and_id(options) - if specified_id.blank? && options["id"].present? - options["id"] += "_#{sanitized_value(tag_value)}" + if specified_id.blank? && options["id"].present? + options["id"] += "_#{sanitized_value(tag_value)}" + end end end - end - def add_default_name_and_id(options) - index = name_and_id_index(options) - options["name"] = options.fetch("name"){ tag_name(options["multiple"], index) } - options["id"] = options.fetch("id"){ tag_id(index) } - if namespace = options.delete("namespace") - options["id"] = options["id"] ? "#{namespace}_#{options['id']}" : namespace + def add_default_name_and_id(options) + index = name_and_id_index(options) + options["name"] = options.fetch("name"){ tag_name(options["multiple"], index) } + options["id"] = options.fetch("id"){ tag_id(index) } + if namespace = options.delete("namespace") + options["id"] = options["id"] ? "#{namespace}_#{options['id']}" : namespace + end end - end - def tag_name(multiple = false, index = nil) - # a little duplication to construct less strings - if index - "#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}" - else - "#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}" + def tag_name(multiple = false, index = nil) + # a little duplication to construct less strings + if index + "#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}" + else + "#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}" + end end - end - def tag_id(index = nil) - # a little duplication to construct less strings - if index - "#{sanitized_object_name}_#{index}_#{sanitized_method_name}" - else - "#{sanitized_object_name}_#{sanitized_method_name}" + def tag_id(index = nil) + # a little duplication to construct less strings + if index + "#{sanitized_object_name}_#{index}_#{sanitized_method_name}" + else + "#{sanitized_object_name}_#{sanitized_method_name}" + end end - end - def sanitized_object_name - @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "") - end + def sanitized_object_name + @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "") + end - def sanitized_method_name - @sanitized_method_name ||= @method_name.sub(/\?$/,"") - end + def sanitized_method_name + @sanitized_method_name ||= @method_name.sub(/\?$/,"") + end - def sanitized_value(value) - value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase - end + def sanitized_value(value) + value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase + end - def select_content_tag(option_tags, options, html_options) - html_options = html_options.stringify_keys - add_default_name_and_id(html_options) + def select_content_tag(option_tags, options, html_options) + html_options = html_options.stringify_keys + add_default_name_and_id(html_options) - if placeholder_required?(html_options) - raise ArgumentError, "include_blank cannot be false for a required field." if options[:include_blank] == false - options[:include_blank] ||= true unless options[:prompt] - end + if placeholder_required?(html_options) + raise ArgumentError, "include_blank cannot be false for a required field." if options[:include_blank] == false + options[:include_blank] ||= true unless options[:prompt] + end - value = options.fetch(:selected) { value(object) } - select = content_tag("select", add_options(option_tags, options, value), html_options) + value = options.fetch(:selected) { value(object) } + select = content_tag("select", add_options(option_tags, options, value), html_options) - if html_options["multiple"] && options.fetch(:include_hidden, true) - tag("input", disabled: html_options["disabled"], name: html_options["name"], type: "hidden", value: "") + select - else - select + if html_options["multiple"] && options.fetch(:include_hidden, true) + tag("input", disabled: html_options["disabled"], name: html_options["name"], type: "hidden", value: "") + select + else + select + end end - end - def placeholder_required?(html_options) - # See https://html.spec.whatwg.org/multipage/forms.html#attr-select-required - html_options["required"] && !html_options["multiple"] && html_options.fetch("size", 1).to_i == 1 - end - - def add_options(option_tags, options, value = nil) - if options[:include_blank] - option_tags = tag_builder.content_tag_string("option", options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, value: "") + "\n" + option_tags + def placeholder_required?(html_options) + # See https://html.spec.whatwg.org/multipage/forms.html#attr-select-required + html_options["required"] && !html_options["multiple"] && html_options.fetch("size", 1).to_i == 1 end - if value.blank? && options[:prompt] - option_tags = tag_builder.content_tag_string("option", prompt_text(options[:prompt]), value: "") + "\n" + option_tags + + def add_options(option_tags, options, value = nil) + if options[:include_blank] + option_tags = tag_builder.content_tag_string("option", options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, value: "") + "\n" + option_tags + end + if value.blank? && options[:prompt] + option_tags = tag_builder.content_tag_string("option", prompt_text(options[:prompt]), value: "") + "\n" + option_tags + end + option_tags end - option_tags - end - def name_and_id_index(options) - options.key?("index") ? options.delete("index") || "" : @auto_index - end + def name_and_id_index(options) + options.key?("index") ? options.delete("index") || "" : @auto_index + end end end end diff --git a/actionview/lib/action_view/helpers/tags/check_box.rb b/actionview/lib/action_view/helpers/tags/check_box.rb index 653643d692..02f87fc89f 100644 --- a/actionview/lib/action_view/helpers/tags/check_box.rb +++ b/actionview/lib/action_view/helpers/tags/check_box.rb @@ -38,26 +38,26 @@ module ActionView private - def checked?(value) - case value - when TrueClass, FalseClass - value == !!@checked_value - when NilClass - false - when String - value == @checked_value - else - if value.respond_to?(:include?) - value.include?(@checked_value) + def checked?(value) + case value + when TrueClass, FalseClass + value == !!@checked_value + when NilClass + false + when String + value == @checked_value else - value.to_i == @checked_value.to_i + if value.respond_to?(:include?) + value.include?(@checked_value) + else + value.to_i == @checked_value.to_i + end end end - end - def hidden_field_for_checkbox(options) - @unchecked_value ? tag("input", options.slice("name", "disabled", "form").merge!("type" => "hidden", "value" => @unchecked_value)) : "".html_safe - end + def hidden_field_for_checkbox(options) + @unchecked_value ? tag("input", options.slice("name", "disabled", "form").merge!("type" => "hidden", "value" => @unchecked_value)) : "".html_safe + end end end end diff --git a/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb b/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb index 59eacbff8b..2a6bf49567 100644 --- a/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb +++ b/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb @@ -20,13 +20,13 @@ module ActionView private - def render_component(builder) - builder.check_box + builder.label - end + def render_component(builder) + builder.check_box + builder.label + end - def hidden_field_name #:nodoc: - "#{super}[]" - end + def hidden_field_name #:nodoc: + "#{super}[]" + end end end end diff --git a/actionview/lib/action_view/helpers/tags/collection_helpers.rb b/actionview/lib/action_view/helpers/tags/collection_helpers.rb index 7607fe64d0..70d7c484eb 100644 --- a/actionview/lib/action_view/helpers/tags/collection_helpers.rb +++ b/actionview/lib/action_view/helpers/tags/collection_helpers.rb @@ -36,81 +36,81 @@ module ActionView private - def instantiate_builder(builder_class, item, value, text, html_options) - builder_class.new(@template_object, @object_name, @method_name, item, - sanitize_attribute_name(value), text, value, html_options) - end + def instantiate_builder(builder_class, item, value, text, html_options) + builder_class.new(@template_object, @object_name, @method_name, item, + sanitize_attribute_name(value), text, value, html_options) + end # Generate default options for collection helpers, such as :checked and # :disabled. - def default_html_options_for_collection(item, value) #:nodoc: - html_options = @html_options.dup - - [:checked, :selected, :disabled, :readonly].each do |option| - current_value = @options[option] - next if current_value.nil? - - accept = if current_value.respond_to?(:call) - current_value.call(item) - else - Array(current_value).map(&:to_s).include?(value.to_s) + def default_html_options_for_collection(item, value) #:nodoc: + html_options = @html_options.dup + + [:checked, :selected, :disabled, :readonly].each do |option| + current_value = @options[option] + next if current_value.nil? + + accept = if current_value.respond_to?(:call) + current_value.call(item) + else + Array(current_value).map(&:to_s).include?(value.to_s) + end + + if accept + html_options[option] = true + elsif option == :checked + html_options[option] = false + end end - if accept - html_options[option] = true - elsif option == :checked - html_options[option] = false - end + html_options[:object] = @object + html_options end - html_options[:object] = @object - html_options - end + def sanitize_attribute_name(value) #:nodoc: + "#{sanitized_method_name}_#{sanitized_value(value)}" + end - def sanitize_attribute_name(value) #:nodoc: - "#{sanitized_method_name}_#{sanitized_value(value)}" - end + def render_collection #:nodoc: + @collection.map do |item| + value = value_for_collection(item, @value_method) + text = value_for_collection(item, @text_method) + default_html_options = default_html_options_for_collection(item, value) + additional_html_options = option_html_attributes(item) - def render_collection #:nodoc: - @collection.map do |item| - value = value_for_collection(item, @value_method) - text = value_for_collection(item, @text_method) - default_html_options = default_html_options_for_collection(item, value) - additional_html_options = option_html_attributes(item) + yield item, value, text, default_html_options.merge(additional_html_options) + end.join.html_safe + end - yield item, value, text, default_html_options.merge(additional_html_options) - end.join.html_safe - end + def render_collection_for(builder_class, &block) #:nodoc: + options = @options.stringify_keys + rendered_collection = render_collection do |item, value, text, default_html_options| + builder = instantiate_builder(builder_class, item, value, text, default_html_options) - def render_collection_for(builder_class, &block) #:nodoc: - options = @options.stringify_keys - rendered_collection = render_collection do |item, value, text, default_html_options| - builder = instantiate_builder(builder_class, item, value, text, default_html_options) + if block_given? + @template_object.capture(builder, &block) + else + render_component(builder) + end + end - if block_given? - @template_object.capture(builder, &block) + # Prepend a hidden field to make sure something will be sent back to the + # server if all radio buttons are unchecked. + if options.fetch("include_hidden", true) + hidden_field + rendered_collection else - render_component(builder) + rendered_collection end end - # Prepend a hidden field to make sure something will be sent back to the - # server if all radio buttons are unchecked. - if options.fetch("include_hidden", true) - hidden_field + rendered_collection - else - rendered_collection + def hidden_field #:nodoc: + hidden_name = @html_options[:name] || hidden_field_name + @template_object.hidden_field_tag(hidden_name, "", id: nil) end - end - def hidden_field #:nodoc: - hidden_name = @html_options[:name] || hidden_field_name - @template_object.hidden_field_tag(hidden_name, "", id: nil) - end - - def hidden_field_name #:nodoc: - "#{tag_name(false, @options[:index])}" - end + def hidden_field_name #:nodoc: + "#{tag_name(false, @options[:index])}" + end end end end diff --git a/actionview/lib/action_view/helpers/tags/date_select.rb b/actionview/lib/action_view/helpers/tags/date_select.rb index 602f393ddb..006605885a 100644 --- a/actionview/lib/action_view/helpers/tags/date_select.rb +++ b/actionview/lib/action_view/helpers/tags/date_select.rb @@ -22,50 +22,50 @@ module ActionView private - def select_type - self.class.select_type - end + def select_type + self.class.select_type + end - def datetime_selector(options, html_options) - datetime = options.fetch(:selected) { value(object) || default_datetime(options) } - @auto_index ||= nil + def datetime_selector(options, html_options) + datetime = options.fetch(:selected) { value(object) || default_datetime(options) } + @auto_index ||= nil - options = options.dup - options[:field_name] = @method_name - options[:include_position] = true - options[:prefix] ||= @object_name - options[:index] = @auto_index if @auto_index && !options.has_key?(:index) + options = options.dup + options[:field_name] = @method_name + options[:include_position] = true + options[:prefix] ||= @object_name + options[:index] = @auto_index if @auto_index && !options.has_key?(:index) - DateTimeSelector.new(datetime, options, html_options) - end + DateTimeSelector.new(datetime, options, html_options) + end - def default_datetime(options) - return if options[:include_blank] || options[:prompt] + def default_datetime(options) + return if options[:include_blank] || options[:prompt] - case options[:default] - when nil - Time.current - when Date, Time - options[:default] - else - default = options[:default].dup + case options[:default] + when nil + Time.current + when Date, Time + options[:default] + else + default = options[:default].dup - # Rename :minute and :second to :min and :sec - default[:min] ||= default[:minute] - default[:sec] ||= default[:second] + # Rename :minute and :second to :min and :sec + default[:min] ||= default[:minute] + default[:sec] ||= default[:second] - time = Time.current + time = Time.current - [:year, :month, :day, :hour, :min, :sec].each do |key| - default[key] ||= time.send(key) - end + [:year, :month, :day, :hour, :min, :sec].each do |key| + default[key] ||= time.send(key) + end - Time.utc( - default[:year], default[:month], default[:day], - default[:hour], default[:min], default[:sec] - ) + Time.utc( + default[:year], default[:month], default[:day], + default[:hour], default[:min], default[:sec] + ) + end end - end end end end diff --git a/actionview/lib/action_view/helpers/tags/radio_button.rb b/actionview/lib/action_view/helpers/tags/radio_button.rb index 1232183dee..43dbd32083 100644 --- a/actionview/lib/action_view/helpers/tags/radio_button.rb +++ b/actionview/lib/action_view/helpers/tags/radio_button.rb @@ -22,9 +22,9 @@ module ActionView private - def checked?(value) - value.to_s == @tag_value.to_s - end + def checked?(value) + value.to_s == @tag_value.to_s + end end end end diff --git a/actionview/lib/action_view/helpers/tags/select.rb b/actionview/lib/action_view/helpers/tags/select.rb index dcfe8ae757..8cc34e3180 100644 --- a/actionview/lib/action_view/helpers/tags/select.rb +++ b/actionview/lib/action_view/helpers/tags/select.rb @@ -32,9 +32,9 @@ module ActionView # # [nil, []] # { nil => [] } - def grouped_choices? - !@choices.empty? && @choices.first.respond_to?(:last) && Array === @choices.first.last - end + def grouped_choices? + !@choices.empty? && @choices.first.respond_to?(:last) && Array === @choices.first.last + end end end end diff --git a/actionview/lib/action_view/helpers/tags/text_field.rb b/actionview/lib/action_view/helpers/tags/text_field.rb index 9201f8d491..4306c3543d 100644 --- a/actionview/lib/action_view/helpers/tags/text_field.rb +++ b/actionview/lib/action_view/helpers/tags/text_field.rb @@ -23,9 +23,9 @@ module ActionView private - def field_type - self.class.field_type - end + def field_type + self.class.field_type + end end end end diff --git a/actionview/lib/action_view/helpers/tags/translator.rb b/actionview/lib/action_view/helpers/tags/translator.rb index 8b6655481d..62b1df81c6 100644 --- a/actionview/lib/action_view/helpers/tags/translator.rb +++ b/actionview/lib/action_view/helpers/tags/translator.rb @@ -16,24 +16,24 @@ module ActionView protected - attr_reader :object_name, :method_and_value, :scope, :model + attr_reader :object_name, :method_and_value, :scope, :model private - def i18n_default - if model - key = model.model_name.i18n_key - ["#{key}.#{method_and_value}".to_sym, ""] - else - "" + def i18n_default + if model + key = model.model_name.i18n_key + ["#{key}.#{method_and_value}".to_sym, ""] + else + "" + end end - end - def human_attribute_name - if model && model.class.respond_to?(:human_attribute_name) - model.class.human_attribute_name(method_and_value) + def human_attribute_name + if model && model.class.respond_to?(:human_attribute_name) + model.class.human_attribute_name(method_and_value) + end end - end end end end diff --git a/actionview/lib/action_view/helpers/text_helper.rb b/actionview/lib/action_view/helpers/text_helper.rb index cb812bd5ba..0fea4df09c 100644 --- a/actionview/lib/action_view/helpers/text_helper.rb +++ b/actionview/lib/action_view/helpers/text_helper.rb @@ -432,17 +432,17 @@ module ActionView private - def next_index - step_index(1) - end + def next_index + step_index(1) + end - def previous_index - step_index(-1) - end + def previous_index + step_index(-1) + end - def step_index(n) - (@index + n) % @values.size - end + def step_index(n) + (@index + n) % @values.size + end end private diff --git a/actionview/lib/action_view/layouts.rb b/actionview/lib/action_view/layouts.rb index f1730a5aae..bf36dde181 100644 --- a/actionview/lib/action_view/layouts.rb +++ b/actionview/lib/action_view/layouts.rb @@ -230,19 +230,19 @@ module ActionView # # ==== Returns # * Boolean - True if the action has a layout definition, false otherwise. - def _conditional_layout? - return unless super + def _conditional_layout? + return unless super - conditions = _layout_conditions + conditions = _layout_conditions - if only = conditions[:only] - only.include?(action_name) - elsif except = conditions[:except] - !except.include?(action_name) - else - true + if only = conditions[:only] + only.include?(action_name) + elsif except = conditions[:except] + !except.include?(action_name) + else + true + end end - end end # Specify the layout to use for this class. @@ -338,9 +338,9 @@ module ActionView # # ==== Returns # * String - A template name - def _implied_layout_name # :nodoc: - controller_path - end + def _implied_layout_name # :nodoc: + controller_path + end end def _normalize_options(options) # :nodoc: diff --git a/actionview/lib/action_view/path_set.rb b/actionview/lib/action_view/path_set.rb index f68d2a77ed..6688519ffd 100644 --- a/actionview/lib/action_view/path_set.rb +++ b/actionview/lib/action_view/path_set.rb @@ -69,30 +69,30 @@ module ActionView #:nodoc: private - def _find_all(path, prefixes, args, outside_app) - prefixes = [prefixes] if String === prefixes - prefixes.each do |prefix| - paths.each do |resolver| - if outside_app - templates = resolver.find_all_anywhere(path, prefix, *args) - else - templates = resolver.find_all(path, prefix, *args) + def _find_all(path, prefixes, args, outside_app) + prefixes = [prefixes] if String === prefixes + prefixes.each do |prefix| + paths.each do |resolver| + if outside_app + templates = resolver.find_all_anywhere(path, prefix, *args) + else + templates = resolver.find_all(path, prefix, *args) + end + return templates unless templates.empty? end - return templates unless templates.empty? end + [] end - [] - end - def typecast(paths) - paths.map do |path| - case path - when Pathname, String - OptimizedFileSystemResolver.new path.to_s - else - path + def typecast(paths) + paths.map do |path| + case path + when Pathname, String + OptimizedFileSystemResolver.new path.to_s + else + path + end end end - end end end diff --git a/actionview/lib/action_view/renderer/abstract_renderer.rb b/actionview/lib/action_view/renderer/abstract_renderer.rb index baff791987..3c85be49cd 100644 --- a/actionview/lib/action_view/renderer/abstract_renderer.rb +++ b/actionview/lib/action_view/renderer/abstract_renderer.rb @@ -27,27 +27,27 @@ module ActionView protected - def extract_details(options) - @lookup_context.registered_details.each_with_object({}) do |key, details| - value = options[key] + def extract_details(options) + @lookup_context.registered_details.each_with_object({}) do |key, details| + value = options[key] - details[key] = Array(value) if value + details[key] = Array(value) if value + end end - end - def instrument(name, **options) - options[:identifier] ||= (@template && @template.identifier) || @path + def instrument(name, **options) + options[:identifier] ||= (@template && @template.identifier) || @path - ActiveSupport::Notifications.instrument("render_#{name}.action_view", options) do |payload| - yield payload + ActiveSupport::Notifications.instrument("render_#{name}.action_view", options) do |payload| + yield payload + end end - end - def prepend_formats(formats) - formats = Array(formats) - return if formats.empty? || @lookup_context.html_fallback_for_js + def prepend_formats(formats) + formats = Array(formats) + return if formats.empty? || @lookup_context.html_fallback_for_js - @lookup_context.formats = formats | @lookup_context.formats - end + @lookup_context.formats = formats | @lookup_context.formats + end end end diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb index 114e4092af..1509726a37 100644 --- a/actionview/lib/action_view/renderer/partial_renderer.rb +++ b/actionview/lib/action_view/renderer/partial_renderer.rb @@ -316,38 +316,38 @@ module ActionView private - def render_collection - instrument(:collection, count: @collection.size) do |payload| - return nil if @collection.blank? + def render_collection + instrument(:collection, count: @collection.size) do |payload| + return nil if @collection.blank? - if @options.key?(:spacer_template) - spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals) - end + if @options.key?(:spacer_template) + spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals) + end - cache_collection_render(payload) do - @template ? collection_with_template : collection_without_template - end.join(spacer).html_safe + cache_collection_render(payload) do + @template ? collection_with_template : collection_without_template + end.join(spacer).html_safe + end end - end - def render_partial - view, locals, block = @view, @locals, @block - object, as = @object, @variable + def render_partial + view, locals, block = @view, @locals, @block + object, as = @object, @variable - if !block && (layout = @options[:layout]) - layout = find_template(layout.to_s, @template_keys) - end + if !block && (layout = @options[:layout]) + layout = find_template(layout.to_s, @template_keys) + end - object = locals[as] if object.nil? # Respect object when object is false - locals[as] = object if @has_object + object = locals[as] if object.nil? # Respect object when object is false + locals[as] = object if @has_object - content = @template.render(view, locals) do |*name| - view._layout_for(*name, &block) - end + content = @template.render(view, locals) do |*name| + view._layout_for(*name, &block) + end - content = layout.render(view, locals){ content } if layout - content - end + content = layout.render(view, locals){ content } if layout + content + end # Sets up instance variables needed for rendering a partial. This method # finds the options and details and extracts them. The method also contains @@ -356,114 +356,114 @@ module ActionView # If +options[:partial]+ is a string, then the +@path+ instance variable is # set to that string. Otherwise, the +options[:partial]+ object must # respond to +to_partial_path+ in order to setup the path. - def setup(context, options, block) - @view = context - @options = options - @block = block + def setup(context, options, block) + @view = context + @options = options + @block = block - @locals = options[:locals] || {} - @details = extract_details(options) + @locals = options[:locals] || {} + @details = extract_details(options) - prepend_formats(options[:formats]) + prepend_formats(options[:formats]) - partial = options[:partial] + partial = options[:partial] - if String === partial - @has_object = options.key?(:object) - @object = options[:object] - @collection = collection_from_options - @path = partial - else - @has_object = true - @object = partial - @collection = collection_from_object || collection_from_options + if String === partial + @has_object = options.key?(:object) + @object = options[:object] + @collection = collection_from_options + @path = partial + else + @has_object = true + @object = partial + @collection = collection_from_object || collection_from_options + + if @collection + paths = @collection_data = @collection.map { |o| partial_path(o) } + @path = paths.uniq.one? ? paths.first : nil + else + @path = partial_path + end + end - if @collection - paths = @collection_data = @collection.map { |o| partial_path(o) } - @path = paths.uniq.one? ? paths.first : nil + if as = options[:as] + raise_invalid_option_as(as) unless /\A[a-z_]\w*\z/.match?(as.to_s) + as = as.to_sym + end + + if @path + @variable, @variable_counter, @variable_iteration = retrieve_variable(@path, as) + @template_keys = retrieve_template_keys else - @path = partial_path + paths.map! { |path| retrieve_variable(path, as).unshift(path) } end + + self end - if as = options[:as] - raise_invalid_option_as(as) unless /\A[a-z_]\w*\z/.match?(as.to_s) - as = as.to_sym + def collection_from_options + if @options.key?(:collection) + collection = @options[:collection] + collection ? collection.to_a : [] + end end - if @path - @variable, @variable_counter, @variable_iteration = retrieve_variable(@path, as) - @template_keys = retrieve_template_keys - else - paths.map! { |path| retrieve_variable(path, as).unshift(path) } + def collection_from_object + @object.to_ary if @object.respond_to?(:to_ary) end - self - end + def find_partial + find_template(@path, @template_keys) if @path + end - def collection_from_options - if @options.key?(:collection) - collection = @options[:collection] - collection ? collection.to_a : [] + def find_template(path, locals) + prefixes = path.include?(?/) ? [] : @lookup_context.prefixes + @lookup_context.find_template(path, prefixes, true, locals, @details) end - end - def collection_from_object - @object.to_ary if @object.respond_to?(:to_ary) - end + def collection_with_template + view, locals, template = @view, @locals, @template + as, counter, iteration = @variable, @variable_counter, @variable_iteration - def find_partial - find_template(@path, @template_keys) if @path - end + if layout = @options[:layout] + layout = find_template(layout, @template_keys) + end - def find_template(path, locals) - prefixes = path.include?(?/) ? [] : @lookup_context.prefixes - @lookup_context.find_template(path, prefixes, true, locals, @details) - end + partial_iteration = PartialIteration.new(@collection.size) + locals[iteration] = partial_iteration - def collection_with_template - view, locals, template = @view, @locals, @template - as, counter, iteration = @variable, @variable_counter, @variable_iteration + @collection.map do |object| + locals[as] = object + locals[counter] = partial_iteration.index - if layout = @options[:layout] - layout = find_template(layout, @template_keys) + content = template.render(view, locals) + content = layout.render(view, locals) { content } if layout + partial_iteration.iterate! + content + end end - partial_iteration = PartialIteration.new(@collection.size) - locals[iteration] = partial_iteration - - @collection.map do |object| - locals[as] = object - locals[counter] = partial_iteration.index - - content = template.render(view, locals) - content = layout.render(view, locals) { content } if layout - partial_iteration.iterate! - content - end - end + def collection_without_template + view, locals, collection_data = @view, @locals, @collection_data + cache = {} + keys = @locals.keys - def collection_without_template - view, locals, collection_data = @view, @locals, @collection_data - cache = {} - keys = @locals.keys + partial_iteration = PartialIteration.new(@collection.size) - partial_iteration = PartialIteration.new(@collection.size) + @collection.map do |object| + index = partial_iteration.index + path, as, counter, iteration = collection_data[index] - @collection.map do |object| - index = partial_iteration.index - path, as, counter, iteration = collection_data[index] + locals[as] = object + locals[counter] = index + locals[iteration] = partial_iteration - locals[as] = object - locals[counter] = index - locals[iteration] = partial_iteration - - template = (cache[path] ||= find_template(path, keys + [as, counter])) - content = template.render(view, locals) - partial_iteration.iterate! - content + template = (cache[path] ||= find_template(path, keys + [as, counter])) + content = template.render(view, locals) + partial_iteration.iterate! + content + end end - end # Obtains the path to where the object's partial is located. If the object # responds to +to_partial_path+, then +to_partial_path+ will be called and @@ -472,79 +472,79 @@ module ActionView # # If +prefix_partial_path_with_controller_namespace+ is true, then this # method will prefix the partial paths with a namespace. - def partial_path(object = @object) - object = object.to_model if object.respond_to?(:to_model) + def partial_path(object = @object) + object = object.to_model if object.respond_to?(:to_model) - path = if object.respond_to?(:to_partial_path) - object.to_partial_path - else - raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.") + path = if object.respond_to?(:to_partial_path) + object.to_partial_path + else + raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.") + end + + if @view.prefix_partial_path_with_controller_namespace + prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup) + else + path + end end - if @view.prefix_partial_path_with_controller_namespace - prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup) - else - path + def prefixed_partial_names + @prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix] end - end - def prefixed_partial_names - @prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix] - end + def merge_prefix_into_object_path(prefix, object_path) + if prefix.include?(?/) && object_path.include?(?/) + prefixes = [] + prefix_array = File.dirname(prefix).split("/") + object_path_array = object_path.split("/")[0..-3] # skip model dir & partial - def merge_prefix_into_object_path(prefix, object_path) - if prefix.include?(?/) && object_path.include?(?/) - prefixes = [] - prefix_array = File.dirname(prefix).split("/") - object_path_array = object_path.split("/")[0..-3] # skip model dir & partial + prefix_array.each_with_index do |dir, index| + break if dir == object_path_array[index] + prefixes << dir + end - prefix_array.each_with_index do |dir, index| - break if dir == object_path_array[index] - prefixes << dir + (prefixes << object_path).join("/") + else + object_path end - - (prefixes << object_path).join("/") - else - object_path end - end - def retrieve_template_keys - keys = @locals.keys - keys << @variable if @has_object || @collection - if @collection - keys << @variable_counter - keys << @variable_iteration + def retrieve_template_keys + keys = @locals.keys + keys << @variable if @has_object || @collection + if @collection + keys << @variable_counter + keys << @variable_iteration + end + keys end - keys - end - def retrieve_variable(path, as) - variable = as || begin - base = path[-1] == "/".freeze ? "".freeze : File.basename(path) - raise_invalid_identifier(path) unless base =~ /\A_?(.*?)(?:\.\w+)*\z/ - $1.to_sym - end - if @collection - variable_counter = :"#{variable}_counter" - variable_iteration = :"#{variable}_iteration" + def retrieve_variable(path, as) + variable = as || begin + base = path[-1] == "/".freeze ? "".freeze : File.basename(path) + raise_invalid_identifier(path) unless base =~ /\A_?(.*?)(?:\.\w+)*\z/ + $1.to_sym + end + if @collection + variable_counter = :"#{variable}_counter" + variable_iteration = :"#{variable}_iteration" + end + [variable, variable_counter, variable_iteration] end - [variable, variable_counter, variable_iteration] - end - IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " + - "make sure your partial name starts with underscore." + IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " + + "make sure your partial name starts with underscore." - OPTION_AS_ERROR_MESSAGE = "The value (%s) of the option `as` is not a valid Ruby identifier; " + - "make sure it starts with lowercase letter, " + - "and is followed by any combination of letters, numbers and underscores." + OPTION_AS_ERROR_MESSAGE = "The value (%s) of the option `as` is not a valid Ruby identifier; " + + "make sure it starts with lowercase letter, " + + "and is followed by any combination of letters, numbers and underscores." - def raise_invalid_identifier(path) - raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path)) - end + def raise_invalid_identifier(path) + raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path)) + end - def raise_invalid_option_as(as) - raise ArgumentError.new(OPTION_AS_ERROR_MESSAGE % (as)) - end + def raise_invalid_option_as(as) + raise ArgumentError.new(OPTION_AS_ERROR_MESSAGE % (as)) + 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 f49cf589f8..0323ebef6a 100644 --- a/actionview/lib/action_view/renderer/streaming_template_renderer.rb +++ b/actionview/lib/action_view/renderer/streaming_template_renderer.rb @@ -29,15 +29,15 @@ module ActionView # This is the same logging logic as in ShowExceptions middleware. # TODO Once "exceptron" is in, refactor this piece to simply re-use exceptron. - def log_error(exception) #:nodoc: - logger = ActionView::Base.logger - return unless logger - - message = "\n#{exception.class} (#{exception.message}):\n" - message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code) - message << " " << exception.backtrace.join("\n ") - logger.fatal("#{message}\n\n") - end + def log_error(exception) #:nodoc: + logger = ActionView::Base.logger + return unless logger + + message = "\n#{exception.class} (#{exception.message}):\n" + message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code) + message << " " << exception.backtrace.join("\n ") + logger.fatal("#{message}\n\n") + end end # For streaming, instead of rendering a given a template, we return a Body @@ -56,48 +56,48 @@ module ActionView private - def delayed_render(buffer, template, layout, view, locals) - # Wrap the given buffer in the StreamingBuffer and pass it to the - # underlying template handler. Now, every time something is concatenated - # to the buffer, it is not appended to an array, but streamed straight - # to the client. - output = ActionView::StreamingBuffer.new(buffer) - yielder = lambda { |*name| view._layout_for(*name) } - - instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do - fiber = Fiber.new do - if layout - layout.render(view, locals, output, &yielder) - else - # If you don't have a layout, just render the thing - # and concatenate the final result. This is the same - # as a layout with just <%= yield %> - output.safe_concat view._layout_for + def delayed_render(buffer, template, layout, view, locals) + # Wrap the given buffer in the StreamingBuffer and pass it to the + # underlying template handler. Now, every time something is concatenated + # to the buffer, it is not appended to an array, but streamed straight + # to the client. + output = ActionView::StreamingBuffer.new(buffer) + yielder = lambda { |*name| view._layout_for(*name) } + + instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do + fiber = Fiber.new do + if layout + layout.render(view, locals, output, &yielder) + else + # If you don't have a layout, just render the thing + # and concatenate the final result. This is the same + # as a layout with just <%= yield %> + output.safe_concat view._layout_for + end end - end - # Set the view flow to support streaming. It will be aware - # when to stop rendering the layout because it needs to search - # something in the template and vice-versa. - view.view_flow = StreamingFlow.new(view, fiber) + # Set the view flow to support streaming. It will be aware + # when to stop rendering the layout because it needs to search + # something in the template and vice-versa. + view.view_flow = StreamingFlow.new(view, fiber) - # Yo! Start the fiber! - fiber.resume + # Yo! Start the fiber! + fiber.resume - # If the fiber is still alive, it means we need something - # from the template, so start rendering it. If not, it means - # the layout exited without requiring anything from the template. - if fiber.alive? - content = template.render(view, locals, &yielder) + # If the fiber is still alive, it means we need something + # from the template, so start rendering it. If not, it means + # the layout exited without requiring anything from the template. + if fiber.alive? + content = template.render(view, locals, &yielder) - # Once rendering the template is done, sets its content in the :layout key. - view.view_flow.set(:layout, content) + # Once rendering the template is done, sets its content in the :layout key. + view.view_flow.set(:layout, content) - # In case the layout continues yielding, we need to resume - # the fiber until all yields are handled. - fiber.resume while fiber.alive? + # In case the layout continues yielding, we need to resume + # the fiber until all yields are handled. + fiber.resume while fiber.alive? + end end end - end end end diff --git a/actionview/lib/action_view/renderer/template_renderer.rb b/actionview/lib/action_view/renderer/template_renderer.rb index 333413c4a1..0151653b73 100644 --- a/actionview/lib/action_view/renderer/template_renderer.rb +++ b/actionview/lib/action_view/renderer/template_renderer.rb @@ -17,86 +17,86 @@ module ActionView private # Determine the template to be rendered using the given options. - def determine_template(options) - keys = options.has_key?(:locals) ? options[:locals].keys : [] + def determine_template(options) + keys = options.has_key?(:locals) ? options[:locals].keys : [] - if options.key?(:body) - Template::Text.new(options[:body]) - elsif options.key?(:text) - Template::Text.new(options[:text], formats.first) - elsif options.key?(:plain) - Template::Text.new(options[:plain]) - elsif options.key?(:html) - Template::HTML.new(options[:html], formats.first) - elsif options.key?(:file) - 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) - elsif options.key?(:template) - if options[:template].respond_to?(:render) - options[:template] + if options.key?(:body) + Template::Text.new(options[:body]) + elsif options.key?(:text) + Template::Text.new(options[:text], formats.first) + elsif options.key?(:plain) + Template::Text.new(options[:plain]) + elsif options.key?(:html) + Template::HTML.new(options[:html], formats.first) + elsif options.key?(:file) + 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) + elsif options.key?(:template) + if options[:template].respond_to?(:render) + options[:template] + else + find_template(options[:template], options[:prefixes], false, keys, @details) + end else - find_template(options[:template], options[:prefixes], false, keys, @details) + raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :html, :text or :body option." end - else - raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :html, :text or :body option." end - end # Renders the given template. A string representing the layout can be # supplied as well. - def render_template(template, layout_name = nil, locals = nil) #:nodoc: - view, locals = @view, locals || {} + def render_template(template, layout_name = nil, locals = nil) #:nodoc: + view, locals = @view, locals || {} - render_with_layout(layout_name, locals) do |layout| - instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do - template.render(view, locals) { |*name| view._layout_for(*name) } + render_with_layout(layout_name, 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 - end - def render_with_layout(path, locals) #:nodoc: - layout = path && find_layout(path, locals.keys, [formats.first]) - content = yield(layout) + def render_with_layout(path, locals) #:nodoc: + layout = path && find_layout(path, locals.keys, [formats.first]) + content = yield(layout) - if layout - view = @view - view.view_flow.set(:layout, content) - layout.render(view, locals){ |*name| view._layout_for(*name) } - else - content + if layout + view = @view + view.view_flow.set(:layout, content) + layout.render(view, locals){ |*name| view._layout_for(*name) } + else + content + end end - end # This is the method which actually finds the layout using details in the lookup # context object. If no layout is found, it checks if at least a layout with # the given name exists across all details before raising the error. - def find_layout(layout, keys, formats) - resolve_layout(layout, keys, formats) - end + def find_layout(layout, keys, formats) + resolve_layout(layout, keys, formats) + end - def resolve_layout(layout, keys, formats) - details = @details.dup - details[:formats] = formats + def resolve_layout(layout, keys, formats) + details = @details.dup + details[:formats] = formats - case layout - when String - begin - if layout.start_with?("/") - with_fallbacks { find_template(layout, nil, false, [], details) } - else - find_template(layout, nil, false, [], details) + case layout + when String + begin + if layout.start_with?("/") + with_fallbacks { find_template(layout, nil, false, [], details) } + else + find_template(layout, nil, false, [], details) + end + rescue ActionView::MissingTemplate + all_details = @details.merge(formats: @lookup_context.default_formats) + raise unless template_exists?(layout, nil, false, [], all_details) end - rescue ActionView::MissingTemplate - all_details = @details.merge(formats: @lookup_context.default_formats) - raise unless template_exists?(layout, nil, false, [], all_details) + when Proc + resolve_layout(layout.call(formats), keys, formats) + else + layout end - when Proc - resolve_layout(layout.call(formats), keys, formats) - else - layout end - end end end diff --git a/actionview/lib/action_view/template/handlers/builder.rb b/actionview/lib/action_view/template/handlers/builder.rb index d90b0c6378..e08a5b5db8 100644 --- a/actionview/lib/action_view/template/handlers/builder.rb +++ b/actionview/lib/action_view/template/handlers/builder.rb @@ -15,12 +15,12 @@ module ActionView protected - def require_engine - @required ||= begin - require "builder" - true + def require_engine + @required ||= begin + require "builder" + true + end end - end end end end diff --git a/actionview/lib/action_view/template/resolver.rb b/actionview/lib/action_view/template/resolver.rb index 6a7baf4fbc..33d60be144 100644 --- a/actionview/lib/action_view/template/resolver.rb +++ b/actionview/lib/action_view/template/resolver.rb @@ -107,22 +107,22 @@ module ActionView private - def canonical_no_templates(templates) - templates.empty? ? NO_TEMPLATES : templates - end - - def templates_have_changed?(cached_templates, fresh_templates) - # if either the old or new template list is empty, we don't need to (and can't) - # compare modification times, and instead just check whether the lists are different - if cached_templates.blank? || fresh_templates.blank? - return fresh_templates.blank? != cached_templates.blank? + def canonical_no_templates(templates) + templates.empty? ? NO_TEMPLATES : templates end - cached_templates_max_updated_at = cached_templates.map(&:updated_at).max + def templates_have_changed?(cached_templates, fresh_templates) + # if either the old or new template list is empty, we don't need to (and can't) + # compare modification times, and instead just check whether the lists are different + if cached_templates.blank? || fresh_templates.blank? + return fresh_templates.blank? != cached_templates.blank? + end - # if a template has changed, it will be now be newer than all the cached templates - fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at } - end + cached_templates_max_updated_at = cached_templates.map(&:updated_at).max + + # if a template has changed, it will be now be newer than all the cached templates + fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at } + end end cattr_accessor :caching @@ -214,93 +214,93 @@ module ActionView private - def find_templates(name, prefix, partial, details, outside_app_allowed = false) - path = Path.build(name, prefix, partial) - query(path, details, details[:formats], outside_app_allowed) - end + def find_templates(name, prefix, partial, details, outside_app_allowed = false) + path = Path.build(name, prefix, partial) + query(path, details, details[:formats], outside_app_allowed) + end - def query(path, details, formats, outside_app_allowed) - query = build_query(path, details) + def query(path, details, formats, outside_app_allowed) + query = build_query(path, details) - template_paths = find_template_paths(query) - template_paths = reject_files_external_to_app(template_paths) unless outside_app_allowed + template_paths = find_template_paths(query) + template_paths = reject_files_external_to_app(template_paths) unless outside_app_allowed - template_paths.map do |template| - handler, format, variant = extract_handler_and_format_and_variant(template, formats) - contents = File.binread(template) + template_paths.map do |template| + handler, format, variant = extract_handler_and_format_and_variant(template, formats) + contents = File.binread(template) - Template.new(contents, File.expand_path(template), handler, - virtual_path: path.virtual, - format: format, - variant: variant, - updated_at: mtime(template) - ) + Template.new(contents, File.expand_path(template), handler, + virtual_path: path.virtual, + format: format, + variant: variant, + updated_at: mtime(template) + ) + end end - end - def reject_files_external_to_app(files) - files.reject { |filename| !inside_path?(@path, filename) } - end + def reject_files_external_to_app(files) + files.reject { |filename| !inside_path?(@path, filename) } + end - def find_template_paths(query) - Dir[query].uniq.reject do |filename| - File.directory?(filename) || - # deals with case-insensitive file systems. - !File.fnmatch(query, filename, File::FNM_EXTGLOB) + def find_template_paths(query) + Dir[query].uniq.reject do |filename| + File.directory?(filename) || + # deals with case-insensitive file systems. + !File.fnmatch(query, filename, File::FNM_EXTGLOB) + end end - end - def inside_path?(path, filename) - filename = File.expand_path(filename) - path = File.join(path, "") - filename.start_with?(path) - end + def inside_path?(path, filename) + filename = File.expand_path(filename) + path = File.join(path, "") + filename.start_with?(path) + end # Helper for building query glob string based on resolver's pattern. - def build_query(path, details) - query = @pattern.dup + def build_query(path, details) + query = @pattern.dup - prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1" - query.gsub!(/:prefix(\/)?/, prefix) + prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1" + query.gsub!(/:prefix(\/)?/, prefix) - partial = escape_entry(path.partial? ? "_#{path.name}" : path.name) - query.gsub!(/:action/, partial) + partial = escape_entry(path.partial? ? "_#{path.name}" : path.name) + query.gsub!(/:action/, partial) - details.each do |ext, candidates| - if ext == :variants && candidates == :any - query.gsub!(/:#{ext}/, "*") - else - query.gsub!(/:#{ext}/, "{#{candidates.compact.uniq.join(',')}}") + details.each do |ext, candidates| + if ext == :variants && candidates == :any + query.gsub!(/:#{ext}/, "*") + else + query.gsub!(/:#{ext}/, "{#{candidates.compact.uniq.join(',')}}") + end end - end - File.expand_path(query, @path) - end + File.expand_path(query, @path) + end - def escape_entry(entry) - entry.gsub(/[*?{}\[\]]/, '\\\\\\&'.freeze) - end + def escape_entry(entry) + entry.gsub(/[*?{}\[\]]/, '\\\\\\&'.freeze) + end # Returns the file mtime from the filesystem. - def mtime(p) - File.mtime(p) - end + def mtime(p) + File.mtime(p) + end # Extract handler, formats and variant from path. If a format cannot be found neither # from the path, or the handler, we should return the array of formats given # to the resolver. - def extract_handler_and_format_and_variant(path, default_formats) - pieces = File.basename(path).split(".".freeze) - pieces.shift + def extract_handler_and_format_and_variant(path, default_formats) + pieces = File.basename(path).split(".".freeze) + pieces.shift - extension = pieces.pop + extension = pieces.pop - handler = Template.handler_for_extension(extension) - format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last - format &&= Template::Types[format] + handler = Template.handler_for_extension(extension) + format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last + format &&= Template::Types[format] - [handler, format, variant] - end + [handler, format, variant] + end end # A resolver that loads files from the filesystem. It allows setting your own diff --git a/actionview/lib/action_view/view_paths.rb b/actionview/lib/action_view/view_paths.rb index b07940195d..6b6cbcf06a 100644 --- a/actionview/lib/action_view/view_paths.rb +++ b/actionview/lib/action_view/view_paths.rb @@ -24,9 +24,9 @@ module ActionView # Override this method in your controller if you want to change paths prefixes for finding views. # Prefixes defined here will still be added to parents' ._prefixes. - def local_prefixes - [controller_path] - end + def local_prefixes + [controller_path] + end end # The prefixes used in render "foo" shortcuts. -- cgit v1.2.3