Commit Graph

2615 Commits

Author SHA1 Message Date
Akira Matsuda
94ce451e6e Time#[:year, :month, :day, :hour, :min, :sec] are public methods 2020-10-02 14:12:45 +09:00
Vinicius Stock
ecbde46a40
Save some allocations in ActionView digest 2020-09-19 14:03:05 -04:00
Eugene Kenny
0b244ff44c
Merge pull request #39989 from jonathanhefner/translate-refactor
Improve Action View `translate` helper
2020-09-16 17:01:45 +01:00
Jonathan Hefner
d81926fdac Improve Action View translate helper
This disentangles the control flow between Action View's `translate` and
I18n's `translate`.  In doing so, it fixes a handful of corner cases,
for which tests have now been added.  It also reduces memory
allocations, and improves speed when using a default:

**Memory**

```ruby
require "benchmark/memory"

Benchmark.memory do |x|
  x.report("warmup") { translate(:"translations.foo"); translate(:"translations.html") }
  x.report("text") { translate(:"translations.foo") }
  x.report("html") { translate(:"translations.html") }
  x.report("text 1 default") { translate(:"translations.missing", default: :"translations.foo") }
  x.report("html 1 default") { translate(:"translations.missing", default: :"translations.html") }
  x.report("text 2 defaults") { translate(:"translations.missing", default: [:"translations.missing", :"translations.foo"]) }
  x.report("html 2 defaults") { translate(:"translations.missing", default: [:"translations.missing", :"translations.html"]) }
end
```

Before:

```
                text     1.240k memsize (     0.000  retained)
                        13.000  objects (     0.000  retained)
                         2.000  strings (     0.000  retained)
                html     1.600k memsize (     0.000  retained)
                        19.000  objects (     0.000  retained)
                         2.000  strings (     0.000  retained)
      text 1 default     4.728k memsize (     1.200k retained)
                        39.000  objects (     4.000  retained)
                         5.000  strings (     0.000  retained)
      html 1 default     5.056k memsize (     1.160k retained)
                        41.000  objects (     3.000  retained)
                         4.000  strings (     0.000  retained)
     text 2 defaults     7.464k memsize (     2.392k retained)
                        54.000  objects (     6.000  retained)
                         4.000  strings (     0.000  retained)
     html 2 defaults     7.944k memsize (     2.384k retained)
                        60.000  objects (     6.000  retained)
                         4.000  strings (     0.000  retained)
```

After:

```
                text   952.000  memsize (     0.000  retained)
                         9.000  objects (     0.000  retained)
                         1.000  strings (     0.000  retained)
                html     1.008k memsize (     0.000  retained)
                        10.000  objects (     0.000  retained)
                         1.000  strings (     0.000  retained)
      text 1 default     2.400k memsize (    40.000  retained)
                        24.000  objects (     1.000  retained)
                         4.000  strings (     0.000  retained)
      html 1 default     2.464k memsize (     0.000  retained)
                        22.000  objects (     0.000  retained)
                         2.000  strings (     0.000  retained)
     text 2 defaults     3.232k memsize (     0.000  retained)
                        30.000  objects (     0.000  retained)
                         2.000  strings (     0.000  retained)
     html 2 defaults     3.456k memsize (     0.000  retained)
                        32.000  objects (     0.000  retained)
                         2.000  strings (     0.000  retained)
```

**Speed**

```ruby
require "benchmark/ips"

Benchmark.ips do |x|
  x.report("text") { translate(:"translations.foo") }
  x.report("html") { translate(:"translations.html") }
  x.report("text 1 default") { translate(:"translations.missing", default: :"translations.foo") }
  x.report("html 1 default") { translate(:"translations.missing", default: :"translations.html") }
  x.report("text 2 defaults") { translate(:"translations.missing", default: [:"translations.missing", :"translations.foo"]) }
  x.report("html 2 defaults") { translate(:"translations.missing", default: [:"translations.missing", :"translations.html"]) }
end
```

Before:

```
                text     35.685k (± 0.7%) i/s -    179.050k in   5.017773s
                html     28.569k (± 3.1%) i/s -    143.871k in   5.040128s
      text 1 default     13.953k (± 2.0%) i/s -     70.737k in   5.071651s
      html 1 default     12.507k (± 0.4%) i/s -     63.546k in   5.080908s
     text 2 defaults      9.103k (± 0.3%) i/s -     46.308k in   5.087323s
     html 2 defaults      8.570k (± 4.3%) i/s -     43.071k in   5.034322s
```

After:

```
                text     36.694k (± 2.0%) i/s -    186.864k in   5.094367s
                html     30.415k (± 0.5%) i/s -    152.900k in   5.027226s
      text 1 default     18.095k (± 2.7%) i/s -     91.086k in   5.036857s
      html 1 default     15.934k (± 1.7%) i/s -     80.223k in   5.036085s
     text 2 defaults     12.179k (± 0.6%) i/s -     61.659k in   5.062910s
     html 2 defaults     11.193k (± 2.1%) i/s -     56.406k in   5.041433s
```
2020-09-16 10:18:54 -05:00
Ryuta Kamizono
c848baffd2 ✂️ [ci skip]
895134bcff (diff-7789e18ec0a61c6845755a257e6eb34fR3)
ee9e308f68 (diff-5e9551294914b338d923032fa904c6beR103)
5f63c771f7 (diff-600d5368b55e46ed961abb4295977ac3R506)
48b6bacbc5 (diff-279ac5c088a3ee7e9f954bbc10d1b773R246)
49adb7f4c6 (diff-0cbe7171fdd7821fd5836896849141c0R111)
9bfe89e68e (diff-9c1c95b001e3680ba8a473cf23508b68R8)
a0f18e6090 (diff-bef0ae2c16dacf77bfd2ba099af8a330R47)
8b4d344815 (diff-09660f59aee7ec893ad609315e8843c5R18)
49d1b5a98d (diff-531e71a9d5fdc8181f38ce4416553694R107)
b674f04756 (diff-7521c0bb452244663b689e77658e63e3R98)
a9012af688 (diff-60bdcf1e1954ec56d41fc4c7bd8d3e39R512)
6380aee182 (diff-5158c234d5e19bb1cffadcbc088400f1R262)
c7820d8124 (diff-f4614e7ba8081c0c9e20fe64b6374228R60)
8df7ed3b88 (diff-0495ed68f82d1bbde593ab5491eab24aR169)
6f94260ac6 (diff-7ecb6672f3fd37dfb79c4539395d3857R28)
03e44f9300 (diff-e9234c4c6668852448059c0a35840bcaR185)
2020-09-16 09:52:10 +09:00
Akira Matsuda
47f5459138 Module#const_set is a public method 2020-09-15 17:19:37 +09:00
Kasper Timm Hansen
f04819972b
Merge pull request #40225 from p8/remove-unused-cache-hit-ivar
Remove unused @cache_hit Hash assignment
2020-09-13 12:35:18 +02:00
Petrik
ebb83e46ba Remove unused @cache_hit Hash assignment
In 2abf6ca0c8304a3cfcdae6e14060b561780be43c @cache_hit got introduced.
This was renamed to @cache_hits and revised in the subsequent commit
8240636beda7b2b487217be1d945eb0d36145c4d but it seems one assignment was
overlooked.
2020-09-13 10:40:28 +02:00
Jonathan Hefner
98a76a50ed Refactor Action View translate helper
This refactor incidentally fixes a corner case when `translate` is
called with a block, the translation is missing, and
`debug_missing_translation` is false.

This commit adds a test for the above corner case, and additional tests
for existing behavior.
2020-09-11 11:56:17 -05:00
Jonathan Hefner
e663f08446
Merge pull request from GHSA-cfjv-5498-mph5
Prior to this commit, when a translation key indicated that the
translation text was HTML, the value returned by `I18n.translate` would
always be marked as `html_safe`.  However, the value returned by
`I18n.translate` could be an untrusted value directly from
`options[:default]`.

This commit ensures values directly from `options[:default]` are not
marked as `html_safe`.
2020-09-09 14:41:31 -04:00
John Hawthorn
758ad13c58 Avoid creating helper modules until modified
In applications which use :all helpers (the default), most controllers
won't be making modifications to their _helpers module.

In CRuby this created many ICLASS objects which could cause a large
increase in memory usage in applications with many controllers and
helpers.

To avoid creating unnecessary modules this PR builds modules only when a
modification is being made: ethier by calling `helper`, `helper_method`,
or through having a default helper (one matching the controller's name)
included onto it.
2020-09-08 16:55:53 -07:00
John Hawthorn
10df6931de
Merge pull request #40125 from jhawthorn/actionview_test_case_isolation
Use a unique controller class per ActionView::TestCase
2020-09-08 14:08:13 -07:00
igor04
a0fe1e77ad Do not use disable_with when it set to false
If automatically_disable_submit_tag is set to false then disable_with
is ignored, as result in all cases where disable_with is explicitly set
to false will produce unexpected result
2020-09-03 19:00:39 +03:00
John Hawthorn
3ec8ddd0cf Avoid module_eval on helpers from AV::TestCase
Previously we were using module_eval to manually add some helpers in
ActionView::TestCase, which assumes a lot about what _helpers allows.

Instead, we can use a standard helper block to define these methods only
one time, and add a method to the new uniq controller class to tie back
to the test instance.
2020-09-02 15:55:01 -07:00
John Hawthorn
65e42c91f5 Use unique controller per ActionView::TestCase
Previously the same class, ActionView::TestCase::TestController, was
used to build a controller for every ActionView::TestCase class.

This caused issues when helpers/helper methods were set directly on the
controller (which from one test we seem to want to support).

This commit solves this by creating a new controller class for every
test case, which gives the controller a unique set of helpers to work
with.

Co-authored-by: John Crepezzi <seejohnrun@github.com>
2020-09-02 15:55:01 -07:00
John Hawthorn
91ae9dfdee Don't override module name on AV::Base subclass
We should avoid overriding name if possible because it is confusing to
developers and it also can causes bugs in code which deal with modules
but aren't using the Module.instance_method(:name).bind workaround.

I believe we can achieve the desired "method missing" behaviour by just
redefining inspect.

Refs https://github.com/rails/rails/pull/39819
2020-09-02 14:47:07 -07:00
Rafael Mendonça França
0edc6c8f64
Remove unecessary method call
All branches that use translated_text are covered so we can remove this
method call.

Also apply some whitespaces around conditionals to make them explicit.
2020-08-26 20:46:33 +00:00
Sean Doyle
7cf52ae981
Extend ActionView::Helpers#translate to yield
This commit extends the `ActionView::Helpers#translate` (and by way of
alias, `#t`) helper methods to accept blocks.

When invoked with a block, the `translate` call will yield the
translated text as its first block argument, along with the resolved
translation key as its second:

```erb
<%= translate(".key") do |translation, resolved_key| %>
  <span data-i18n-key="<%= resolved_key %>"><%= translation %></span>
<% end %>
```

In cases where relative translation keys are foregone in lieu of fully
qualified keys, or if the caller is not interested in the resolved key,
the second block argument can be omitted:

```erb
<%= translate("action.template.key") do |translation| %>
  <p><%= translation %></p>
  <p><%= translation %>, but a second time</p>
<% end %>
```

A benefit of yielding the translation is that it enabled template-local
variable re-use. Alternatively, [`Object#tap`][tap] could be used.

Prior to this commit, however, the resolution of the translation key was
internal to `ActionView`, and unavailable to the caller (unless they
were willing to explicitly determine the resolved key themselves). By
making it available as a block parameter, it could be used to annotate
the translated value in the resulting elements.

[tap]: https://ruby-doc.org/core-2.7.0/Object.html#method-i-tap
2020-08-26 20:46:33 +00:00
Jonathan Fleckenstein
0b65e23978 Allow callers to remove nopush 2020-08-23 09:53:42 -04:00
Jonathan Fleckenstein
033ac18590 don't preload for defered scripts and disable push 2020-08-22 20:59:29 -04:00
nathanallen
cd15412e5a fix documented default values for datetime_select view helper 2020-08-19 16:35:42 -07:00
Eileen M. Uchitelle
443c8470d1
Merge pull request #39939 from Shopify/link-preload-headers
Automatically set Link header for each stylesheet and script
2020-08-17 08:37:22 -04:00
Petrik
a7ed92bd1d Use superclass name in inspect of ActionView::Base.with_empty_template_cache
When rendering views an anonymous subclass is created by calling
ActionView::Base.with_empty_template_cache.
This causes inspect to return an unhelpful description when calling
inspect:
`#<#<Class:0x012345012345>:<0x012345012345>`.

This can be confusing when exceptions are raised because it's hard to
figure out where to look. For example calling an undefined method in a
template would raise the following exception:

    undefined method `undefined' for #<#<Class:0x012345012345>:<0x012345012345>

Instead we can return the non-anonymous superclass name.

    undefined method `undefined' for #<ActionView::Base:0x01234502345>

The anonymous class is created in ActionView::Base.with_empty_template_cache.
See f9bea6304dfba902b1937b3bc29b1ebc2f67e55b
This seems to be done for performance reasons only, without expecting a
change to calling `inspect`.
2020-08-15 11:04:28 +02:00
Yasuo Honda
2d43d47786 Address ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
This pull request fixes #38697

It is caused by `@controller.singleton_class.include @routes.url_helpers` when `@controller` is nil in `ActionController::TestCase`.

* Without this commit

```ruby
% cd actionview
% PARALLEL_WORKERS=1 bin/test test/actionpack/controller/layout_test.rb test/template/url_helper_test.rb --seed 16702 -n "/^(?:LayoutSetInResponseTest#(?:test_layout_symbol_set_in_controller_returning_nil_falls_back_to_default)|UrlHelperTest#(?:test_url_for_with_array_and_only_path_set_to_false))$/"

Run options: --seed 16702 -n "/^(?:LayoutSetInResponseTest#(?:test_layout_symbol_set_in_controller_returning_nil_falls_back_to_default)|UrlHelperTest#(?:test_url_for_with_array_and_only_path_set_to_false))$/"

.E

Error:
UrlHelperTest#test_url_for_with_array_and_only_path_set_to_false:
ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
    /Users/yahonda/src/github.com/rails/rails/actionpack/lib/action_dispatch/http/url.rb:64:in `full_url_for'
    /Users/yahonda/src/github.com/rails/rails/actionpack/lib/action_dispatch/http/url.rb:54:in `url_for'
    /Users/yahonda/src/github.com/rails/rails/actionpack/lib/action_dispatch/routing/route_set.rb:333:in `block in <class:RouteSet>'
    /Users/yahonda/src/github.com/rails/rails/actionpack/lib/action_dispatch/routing/route_set.rb:838:in `url_for'
    /Users/yahonda/src/github.com/rails/rails/actionpack/lib/action_dispatch/routing/route_set.rb:270:in `call'
    /Users/yahonda/src/github.com/rails/rails/actionpack/lib/action_dispatch/routing/route_set.rb:213:in `call'
    /Users/yahonda/src/github.com/rails/rails/actionpack/lib/action_dispatch/routing/route_set.rb:326:in `block in define_url_helper'
    /Users/yahonda/src/github.com/rails/rails/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb:233:in `polymorphic_method'
    /Users/yahonda/src/github.com/rails/rails/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb:116:in `polymorphic_url'
    /Users/yahonda/src/github.com/rails/rails/actionview/lib/action_view/routing_url_for.rb:104:in `url_for'
    /Users/yahonda/src/github.com/rails/rails/actionview/test/template/url_helper_test.rb:102:in `test_url_for_with_array_and_only_path_set_to_false'

bin/test test/template/url_helper_test.rb:100

Finished in 0.042275s, 47.3093 runs/s, 47.3093 assertions/s.
2 runs, 2 assertions, 0 failures, 1 errors, 0 skips
%
```
2020-08-12 19:43:02 +09:00
Yasuo Honda
1e84ac4290 Clear Resolvers' cache after AVLogSubscriberTest tests
Addresses the build failure below:
https://buildkite.com/rails/rails/builds/70853#29647167-4db2-4810-810e-d2c3a4e6dcf8

* This pull request addresses this error.

```
$ bin/test test/template/log_subscriber_test.rb test/template/test_case_test.rb -n "/^(?:AVLogSubscriberTest#(?:test_render_collection_template)|ActionView::HelperInclusionTest#(?:test_helper_class_that_is_being_tested_is_always_included_in_view_instance))$/" --seed 54118
Run options: -n "/^(?:AVLogSubscriberTest#(?:test_render_collection_template)|ActionView::HelperInclusionTest#(?:test_helper_class_that_is_being_tested_is_always_included_in_view_instance))$/" --seed 54118

.E

Error:
ActionView::HelperInclusionTest#test_helper_class_that_is_being_tested_is_always_included_in_view_instance:
ActionView::Template::Error: undefined method `_test__customer_erb___3224798146126036163_10260' for #<#<Class:0x00005653f1b35768>:0x00005653f1b348e0>
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/base.rb:276:in `_run'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/template.rb:182:in `block in render'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/notifications.rb:205:in `instrument'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/template.rb:384:in `instrument_render_template'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/template.rb:180:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:186:in `block in collection_with_template'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:66:in `block in each_with_info'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:66:in `each'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:66:in `each_with_info'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:177:in `each'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:177:in `map'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:177:in `collection_with_template'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:159:in `block (2 levels) in render_collection'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb:21:in `cache_collection_render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:158:in `block in render_collection'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/notifications.rb:203:in `block in instrument'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/notifications/instrumenter.rb:24:in `instrument'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/notifications.rb:203:in `instrument'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:144:in `render_collection'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/collection_renderer.rb:116:in `render_collection_with_partial'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/renderer.rb:75:in `render_partial_to_object'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/renderer.rb:27:in `render_to_object'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/renderer.rb:22:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/helpers/rendering_helper.rb:38:in `block in render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/base.rb:306:in `in_rendering_context'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/helpers/rendering_helper.rb:34:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/test_case.rb:205:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/test/template/test_case_test.rb:126:in `render_from_helper'
    /home/yahonda/src/github.com/rails/rails/actionview/test/fixtures/test/_from_helper.erb:1:in `__home_yahonda_src_github_com_rails_rails_actionview_test_fixtures_test__from_helper_erb___900298654238864924_10340'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/base.rb:276:in `_run'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/template.rb:182:in `block in render'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/notifications.rb:205:in `instrument'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/template.rb:384:in `instrument_render_template'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/template.rb:180:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/partial_renderer.rb:285:in `block in render_partial_template'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/notifications.rb:203:in `block in instrument'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/notifications/instrumenter.rb:24:in `instrument'
    /home/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/notifications.rb:203:in `instrument'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/partial_renderer.rb:280:in `render_partial_template'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/partial_renderer.rb:271:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/renderer.rb:84:in `render_partial_to_object'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/renderer.rb:27:in `render_to_object'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/renderer/renderer.rb:22:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/helpers/rendering_helper.rb:38:in `block in render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/base.rb:306:in `in_rendering_context'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/helpers/rendering_helper.rb:34:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/test_case.rb:205:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/lib/action_view/test_case.rb:122:in `render'
    /home/yahonda/src/github.com/rails/rails/actionview/test/template/test_case_test.rb:136:in `block in <class:HelperInclusionTest>'

bin/test test/template/test_case_test.rb:132

Finished in 0.076637s, 26.0970 runs/s, 39.1454 assertions/s.
2 runs, 3 assertions, 0 failures, 1 errors, 0 skips
$
```

Refer #36189 for the similar fix
2020-07-30 12:14:10 +09:00
Jean Boussier
a9012af688 Automatically set Link header for each stylesheet and script
<link rel="preload"> elements[0] can be serialized in `Link`
headers[1] to allow the browser to preload them before
it parsed the HTML body.

It is particularly useful for scripts included at the bottom
of the document.

[0] https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
[1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
2020-07-28 11:57:36 +02:00
Jonathan Hefner
e6950a332a Add label attribute to <option> from include_blank
The `:include_blank` option of various `<select>`-related helpers causes
an `<option>` element with no content to be rendered.  However, the
[HTML spec] says that unless an `<option>` element has a `label`
attribute (which must be non-empty), its content must be "Text that is
not inter-element whitespace."

In #24923, this issue was addressed for `select_tag` by adding a `label`
attribute to the `<option>`.  This commit addresses the issue in the
same manner for `FormBuilder#select` and various date / time select
helpers.

[HTML spec]: https://html.spec.whatwg.org/multipage/form-elements.html#the-option-element
2020-07-24 15:45:18 -05:00
Jean Boussier
12f3f11f61 Use URI::DEFAULT_PARSER rather than instantiate a new one 2020-06-29 23:06:34 +02:00
pavel
a4583da838 simplify conversion to BINARY 2020-06-24 19:51:20 +02:00
Ross Kaffenberger
04cbaa1475 Use ES module syntax for application.js.tt and docs
This change swaps the CommonJS require() syntax in the Webpacker
application.js pack template file and in documentation examples with ES
module import syntax.

Benefits of this change include:

Provides continuity with the larger frontend community: Arguably, one of
the main draws in adopting Webpacker is its integration with Babel to
support ES module syntax. For a fresh Rails install with Webpacker, the
application.js file will be the first impression most Rails developers
have with webpack and Webpacker.  Most of the recent documentation and
examples they will find online for using other libraries will be based
on ES module syntax.

Reduces confusion: Developers commonly add ES imports to their
application.js pack, typically by following online examples, which means
mixing require() and import statements in a single file. This leads to
confusion and unnecessary friction about differences between require()
and import.

Embraces browser-friendliness: The ES module syntax forward-looking and
is meant to be supported in browsers. On the other hand, require()
syntax is synchronous by design and not browser-supported as CommonJS
originally was adopted in Node.js for server-side JavaScript. That
webpack supports require() syntax is merely a convenience.

Encourages best practices regarding optimization: webpack can statically
analyze ES modules and "tree-shake", i.e., strip out unused exports from
the final build (given certain conditions are met, including
`sideEffects: false` designation in package.json).
2020-06-16 15:12:12 -04:00
Ryuta Kamizono
528b62e386 Address to false negative for Performance/DeletePrefix,DeleteSuffix
Follow up to c07dff72278fb7f2a3c4c71212a0773a2b25c790.

Actually it is not the cop's fault, but we mistakenly use `^`, `$`, and
`\Z` in much places, the cop doesn't correct those conservatively.

I've checked all those usage and replaced all safe ones.
2020-06-14 13:04:47 +09:00
Ryuta Kamizono
cfb7c16ac4 Fixup CHANGELOGs [ci skip] 2020-06-07 12:58:22 +09:00
Jonathan Hefner
08aeb01b0f Lazily build path regex in PathParser
Eagerly building the path regex can exclude handlers which are added on
Action View load.

Fixes #39492.
2020-05-31 15:28:24 -05:00
Eugene Kenny
5888c359e4 Add test for HTML format fallback from JS template
When rendering a template with an explicit JS format, typically via
`respond_to :js`, we want to be able to render HTML partials without
having to specify their format, in order to make SJR more ergonomic.
2020-05-29 22:07:17 +01:00
Ryuta Kamizono
c65864cdca Prefer no allocation start/end_with? over String#[] == 2020-05-29 10:20:13 +09:00
Eugene Kenny
8ae6626b65 Override clear_cache in custom path resolver
https://buildkite.com/rails/rails/builds/69620#ffaa78f1-aba4-42b9-91c8-0fe5d333263a

Since 096d143c8c41c8231c32717372b1bb9c861c739a, when the tests run in
parallel it's possible for `ActionView::LookupContext::DetailsKey.clear`
to be called while this test is running, which wouldn't work correctly.
2020-05-27 21:07:58 +01:00
John Hawthorn
db543ba728
Merge pull request #39361 from jhawthorn/path_parser
Introduce Resolver::PathParser
2020-05-26 20:16:18 -07:00
Aaron Lipman
dd7a673782
Remove redundant @virtual_path variable
Following the introduction of the @current_template variable in 1581cab,
the @virtual_path variable is now redundant, as the value of the virtual
path may be accessed via @current_template.virtual_path. This commit
removes @virtual_path and replaces any references to @virtual_path with
@current_template.virtual_path.
2020-05-26 15:53:11 -04:00
Aaron Lipman
4671fe2040
Ensure cache fragment digests include all templates
A Rails view may rely on several templates (e.g. layouts and partials)
in addition to the template for the action being rendered (e.g.
"show.html.erb"). To track which view file is currently being rendered
for the purpose of generating template tree digests used in cache
fragment keys, Action View uses a stack, the top item of which is
accessed via the @current_template variable (introduced in 1581cab).

Consider the following template:

    <!-- home.html.erb -->
    <%= render layout: "wrapper" do %>
      <%= cache "foo" %>
        HOME
      <%= end %>
    <%= end %>

Inside the block passed to the render helper, @current_template
corresponds to the wrapper.html.erb template instead of home.html.erb.
As wrapper.html.erb is then used as the root node for generating the
template tree digest used in the cache fragment key, the cache fragment
fails to expire upon changes to home.html.erb. Additionally, should a
second template use the wrapper.html.erb layout and contain a cache
fragment with the same key, the cache fragment keys for both templates
will be identical - causing cached content to "leak" from one view to
another (as described in #38984).

This commit skips adding templates to the stack when rendered as a
layout with a block via the render helper, ensuring correct and unique
cache fragment digests. Additionally, the virtual_path keyword arguments
found in CacheHelper and all references to the are removed as they no
longer possess any function. (Following the introduction of
@current_template, virtual_path is accessed via
@current_template.virtual_path rather than as a standalone variable.)
2020-05-26 15:52:05 -04:00
swaggermeister
2a1ec6ed35
Fix typo 2020-05-25 15:00:18 -04:00
Ryuta Kamizono
dc94a753d1 require "active_support/core_ext/symbol/starts_ends_with" for Ruby 2.6
And use `Symbol#[]` to strip suffix to avoid intermediate string
allocation.
2020-05-25 05:24:44 +09:00
Jonathan Hefner
a2ca8f062c Utilize Symbol#start_with? and #end_with?
Follow-up to #39155.

Thanks to Symbol#start_with? and #end_with?, these calls no longer need
to be prefixed with `.to_s`.
2020-05-24 14:46:12 -05:00
fatkodima
e24d6ecbfd Update rubocop-performance gem and enable Performance/DeletePrefix and Performance/DeleteSuffix cops 2020-05-24 12:51:35 +03:00
Vinicius Stock
732372c928
Reduce allocations in action_view cache expiry 2020-05-22 18:38:56 -04:00
Jonathan Hefner
cd2b3be9a6 Allow Erubi bufvar to be configured
This allows `render_in` components that compile their own templates to
use their view context's current output buffer while a
`with_output_buffer` block is being evaluated.

Partially addresses #39377.
2020-05-21 15:22:51 -05:00
John Hawthorn
827119c48b Mark PathParser as :nodoc: 2020-05-19 18:58:44 -07:00
John Hawthorn
e53c45b80c Introduce Resolver::PathParser
The template resolver is supposed to determine the handler, format, and
variant from the path in extract_handler_and_format_and_variant.

Previously this behaviour was close but didn't exactly match the
behaviour of finding templates, and in some cases (particularly with
handlers or formats missing) would return incorrect results.

This commit introduces Resolver::PathParser, a class which should be
able to accurately from any path inside a view directory be able to tell
us exactly the prefix, partial, variant, locale, format, variant, and
handler of that template.

This works by building a building a regexp from the known handlers and
file types. This requires that any resolvers have their cache cleared
when new handlers or types are registered (this was already somewhat the
requirement, since resolver lookups are cached, but this makes it
necessary in more situations).
2020-05-19 18:55:10 -07:00
John Hawthorn
8762d93afc Add tests of resolver variant handling
The template resolver is supposed to determine the handler, format, and
variant from the path in extract_handler_and_format_and_variant.

This commit adds tests for how variants are parsed from the filenames
found in the resolver. It includes two skipped tests which currently fail.
2020-05-19 18:55:10 -07:00
John Hawthorn
dc778f83d7 Only use valid handlers in resolver_shared_tests
We don't have jbuilder installed (this would work if it was).
2020-05-19 18:55:10 -07:00
fatkodima
6c4f3be929 Unify raise_on_missing_translations for views and controllers 2020-05-20 02:42:59 +03:00
Rafael França
a80115b7c5
Merge pull request #39204 from prathamesh-sonpatki/template-annotation
Add the configuration option for annotating templates with file names to the generated app
2020-05-19 19:11:31 -04:00
Prathamesh Sonpatki
a673ce69e7
Rename annotate_template_file_names to annotate_rendered_view_with_filenames
- Add the configuration option for annotating templates with file names to the generated app.
- Add `annotate_rendered_view_with_filenames` option to configuring guide.
2020-05-19 09:28:14 +05:30
Aaron Patterson
b472feddbc
Merge branch 'master-sec'
* master-sec:
  Check that request is same-origin prior to including CSRF token in XHRs
  HMAC raw CSRF token before masking it, so it cannot be used to reconstruct a per-form token
  activesupport: Avoid Marshal.load on raw cache value in RedisCacheStore
  activesupport: Avoid Marshal.load on raw cache value in MemCacheStore
  Return self when calling #each, #each_pair, and #each_value instead of the raw @parameters hash
  Include Content-Length in signature for ActiveStorage direct upload
2020-05-18 08:48:41 -07:00
John Hawthorn
d6a01650aa Skip interpolated strings in AV::Digestor 2020-05-17 15:06:17 -07:00
Jack McCracken
a20fbf9bc5
Check that request is same-origin prior to including CSRF token in XHRs
[CVE-2020-8167]
2020-05-15 16:15:00 -07:00
Ryuta Kamizono
1165401ee9 Remove unused require "active_support/core_ext/kernel/singleton_class"
`singleton_class` is in Ruby 1.9.2, and there is no use singleton class
eval in the files.
2020-05-10 03:20:02 +09:00
John Hawthorn
342f2f0b51
Merge pull request #39164 from jhawthorn/deprecate_dots_take_two
Deprecate rendering templates with . in the name
2020-05-06 09:37:04 -07:00
Ryuta Kamizono
46a22ceaff
Merge pull request #39162 from kamipo/dogfooding_symbol_starts_ends_with
Dogfooding "active_support/core_ext/symbol/starts_ends_with"
2020-05-06 17:19:19 +09:00
John Hawthorn
dd9991bac5 Deprecate rendering templates with . in the name
Allowing templates with "." introduces some ambiguity. Is index.html.erb
a template named "index" with format "html", or is it a template named
"index.html" without a format? We know it's probably the former, but if
we asked ActionView to render "index.html" we would currently get some
combination of the two: a Template with index.html as the name and
virtual path, but with html as the format.

This deprecates having "." anywhere in the template's name, we should
reserve this character for specifying formats. I think in 99% of cases
this will be people specifying `index.html` instead of simply `index`.

This was actually once deprecated in the 3.x series (removed in
6c57177f2c7f4f934716d588545902d5fc00fa99) but I don't think we can rely
on nobody having introduced this in the past 8 years.
2020-05-05 23:21:17 -07:00
John Hawthorn
92d3afe475
Merge pull request #39068 from jhawthorn/dependency_tracker_interpolation
Ignore interpolated strings in DependencyTracker
2020-05-05 23:21:00 -07:00
Ryuta Kamizono
98a1405f07 Dogfooding "active_support/core_ext/symbol/starts_ends_with"
Any missing thing would be found such like #39159.
2020-05-06 14:19:25 +09:00
Godfrey Chan
f4538aa586
Merge pull request #38999 from zvkemp/action-view-instrument-layout
add additional instrumentation block for ActionView layout rendering
2020-05-05 11:50:24 -07:00
Ryuta Kamizono
6a4395f466 Deprecate starts_with? and ends_with? for String core extensions
In the past, we sometimes hit missing `Symbol#start_with?` and
`Symbol#end_with?`.

63256bc5d7
a8e812964d

So I proposed `Symbol#start_with?` and `Symbol#end_with?` to allow duck
typing that methods for String and Symbol, then now it is available in
Ruby 2.7.

https://bugs.ruby-lang.org/issues/16348

Using `String#starts_with?` and `String#ends_with?` could not be gained
that conveniency, so it is preferable to not use these in the future.
2020-05-05 15:51:24 +09:00
Ryuta Kamizono
4642ca9640 Fix actionview tests for missing helper 2020-05-03 06:06:09 +09:00
zvkemp
6380aee182 add additional instrumentation block for ActionView layout rendering 2020-05-01 19:15:54 -07:00
John Hawthorn
1e25f02135 Ignore interpolated strings in DependencyTracker
ActionView::DependencyTracker looks through ERB templates using a regex
to find render calls. Previously this would incorrectly pick up
interpolated strings, like `render "foo/#{bar}"`.

This does not attempt to completely correct DependencyTracker, we can't
parse Ruby accurately with a regex, but should avoid a relatively common
case that previously was generating warnings.
2020-04-27 10:10:45 -07:00
Ryuta Kamizono
977ba0e321 Revert "Update actionview CHANGELOG"
This reverts commit 960ceb237ac886711b8d50cdca3ac13c2e147be8.

Ref #39012, #38858.

[ci skip]
2020-04-27 14:15:00 +09:00
Godfrey Chan
1064c51609 Fix typos [ci skip]
I wrote this shell script to find words from the Rails repo,
so I can paste them into https://www.horsepaste.com/ for
the [codenames game](https://en.m.wikipedia.org/wiki/Codenames_(board_game)).

```bash
git grep -Il '' | \
  grep -v -E "CHANGELOG|Gemfile|gemspec|package\.json|yarn\.lock" | \
  xargs cat | \
  sed '/[^ ]\{10,\}/d' | \
  sed 's/\([A-Z]\)/ \1/g' | \
  tr 'A-Z' 'a-z' | \
  tr -c -s 'a-z' '\n' | \
  sed '/^.\{0,3\}$/d' | \
  sort | \
  uniq | \
  tr '\n' ',' | \
  pbcopy
```

You can see the result in https://www.horsepaste.com/rails-fixed.
Click "Next game" to cycle the words.

Found some typos in the codebase from this 😂

This is how I generated the list of possible typos:

```bash
git grep -Il '' | \
  grep -v -E "CHANGELOG|Gemfile|gemspec|package\.json|yarn\.lock" | \
  xargs cat | \
  sed '/[^ ]\{10,\}/d' | \
  sed 's/\([A-Z]\)/ \1/g' | \
  tr 'A-Z' 'a-z' | \
  tr -c -s 'a-z' '\n' | \
  sed '/^.\{0,3\}$/d' | \
  sort | \
  uniq | \
  aspell --ignore-case list
```

I manually reviewed the list and made the corrections
in this commit. The rest on the list are either:

* Bugs in my script: it split things like "doesn't" into
  "doesn" and "t", if find things like `#ffffff` and
  extracts "ffffff" as a word, etc
* British spelling: honour, optimised
* Foreign words: bonjour, espanol
* Names: nginx, hanekawa
* Technical words: mutex, xhtml
* Portmanteau words: autosave, nodelist
* Invented words: camelize, coachee
* Shortened words: attrs, repo
* Deliberate typos: hllo, hillo (used in code examples, etc)
* Lorem ipsum words: arcu, euismod

This is the [output](https://gist.github.com/chancancode/eb0b573d667dc31906f33f1fb0b22313)
of the script *after* fixing the typos included in this
commit. In theory, someone can run that command again in
the future and compare the output to catch new typos (i.e.
using my list to filter out known typos).

Limitations: the aspell dictionary could be wrong, I
could have miss things, and my script ignores words that
are less than 3 characters or longer than 10 characters.
2020-04-22 21:43:37 -07:00
Jonathan Hefner
e158a34d49 Realign cache key diagram in method doc [ci skip]
Follow-up to #37669.
2020-04-21 23:38:16 -05:00
David Heinemeier Hansson
876cc27609
Revert "Deprecate rendering templates with . in the name" (#39012) 2020-04-21 15:59:46 -07:00
Rafael França
673685cdc8
Merge pull request #38950 from joelhawksley/annotations-error-line
Raise template errors on correct line with annotations enabled
2020-04-14 18:39:25 -04:00
Joel Hawksley
ab8ea48111 Raise errors on correct line with annotations enabled
Co-authored-by: Aaron Patterson <tenderlove@github.com>
2020-04-14 15:26:26 -06:00
Joel Hawksley
dee5d7d23c Pass preamble/postamble to Erubi, reducing coupling 2020-04-14 15:12:21 -06:00
John Hawthorn
5658a43c0c
Merge pull request #38857 from jhawthorn/avoid_instrumentation_indirection
Avoid ActionView rendering instrumentation indirection
2020-04-14 11:57:06 -07:00
Joel Hawksley
3b28486e93 ActionView::Base.annotate_template_file_names only annotates HTML output.
In testing https://github.com/rails/rails/pull/38848 in the
GitHub monolith, we realized that we probably should only
be annotating HTML output with these comments, at least
in their current format. By passing `format` to
`erb_implementation`, we set ourselves up to eventually
support annotations for other formats as well.
2020-04-08 15:22:22 -06:00
John Hawthorn
960ceb237a Update actionview CHANGELOG 2020-04-07 19:23:13 -07:00
John Hawthorn
32b059beb6 Merge pull request #38858 from jhawthorn/deprecate_dots
Deprecate rendering templates with . in the name
2020-04-07 18:39:25 -07:00
Abhay Nikam
bdfffd1355 Update the Rails mailing list URLs to new discuss discourse URL [ci skip] 2020-04-02 22:00:28 +05:30
John Hawthorn
f84773a587 Deprecate rendering templates with . in the name
Allowing templates with "." introduces some ambiguity. Is index.html.erb
a template named "index" with format "html", or is it a template named
"index.html" without a format? We know it's probably the former, but if
we asked ActionView to render "index.html" we would currently get some
combination of the two: a Template with index.html as the name and
virtual path, but with html as the format.

This deprecates having "." anywhere in the template's name, we should
reserve this character for specifying formats. I think in 99% of cases
this will be people specifying `index.html` instead of simply `index`.

This was actually once deprecated in the 3.x series (removed in
6c57177f2c7f4f934716d588545902d5fc00fa99) but I don't think we can rely
on nobody having introduced this in the past 8 years.
2020-03-31 21:55:19 -07:00
John Hawthorn
006bf78b69 Remove AbstractRenderer#instrument 2020-03-31 21:51:51 -07:00
John Hawthorn
f4014f738c Call AS::Notifications.instrument directly in AV
The instrument helper we had here would allocate a new string object for
the key each time it was called and also added two stack frames. The
interpolated strings are also _slightly_ slower to hash since they
aren't fstrings.

Though this was shorter before, I think this is a little more preferable
as a code style since the subscribed keys are now greppable. After this,
there's still one other place this pattern is used (in ActiveSupport
cache).
2020-03-31 21:51:44 -07:00
Joel Hawksley
a59e1de26a .annotate_template_file_names annotates HTML output with template file names
As a developer, when looking at a page in my web browser, it's sometimes
difficult to figure out which template(s) are being used to render the page.

config.action_view.annotate_template_file_names adds HTML comments to the
rendered output indicating where each template begins and ends.

Co-authored-by: Aaron Patterson <tenderlove@github.com>
2020-03-30 14:50:01 -06:00
Josua Schmid
835cf76572
[ci skip] Fix API documentation for link_to_if 2020-03-27 08:08:47 +01:00
Aaron Patterson
fc4ef77d47
Merge pull request #38594 from rails/collection-refactor
Refactoring PartialRenderer
2020-03-23 17:41:20 -07:00
Aaron Patterson
d7bd84bc11
Remove out-of-date comments 2020-03-23 17:21:04 -07:00
Aaron Patterson
033a738817
Fix possible XSS vector in JS escape helper
This commit escapes dollar signs and backticks to prevent JS XSS issues
when using the `j` or `javascript_escape` helper

CVE-2020-5267
2020-03-19 09:48:08 -07:00
Joel Hawksley
c82a9193df
Document view components support (#38656) 2020-03-13 23:52:49 +01:00
Ryuta Kamizono
1ef8c60dfc Avoid extra string allocation in the methods generated by eval 2020-03-10 17:43:35 +09:00
Eugene Kenny
d3599d8aff Use index_by and index_with wherever possible
Using `index_by` or `index_with` is more concise than `each_with_object`
and more performant than `map { ... }.to_h` or `Hash[map { ... }]`.
2020-03-05 01:24:14 +00:00
Aaron Patterson
a15339ff65
remove usless attr_reader 2020-02-28 09:25:25 -08:00
Aaron Patterson
49adb7f4c6
pull preloading behavior in to the collection renderer 2020-02-28 09:23:22 -08:00
Aaron Patterson
72e0d04a4b
Fix issue in ActionText
ActionText was using `render` in a way that ActionView didn't have tests
for.  This is a fix for it.
2020-02-27 16:54:50 -08:00
Aaron Patterson
232372bfd1
Merge branch 'master' into collection-refactor
* master:
  Add a regression test that ActionText caught
  [ci skip] Use yml extension for locale files
  Fix `helper_method` in `ActionView::TestCase` to allow keyword arguments
  Fix `delegate_missing_to` to allow keyword arguments
  Dump the schema or structure of a database when calling db:migrate:name
  Reset the `ActiveRecord::Base` connection after `rails db:migrate:name`
  Fix `unscope` when an `eq` node which has no arel attribute
  Remove unused argument
  Disallow calling `connected_to` on subclasses of `ActiveRecord::Base`
  More less and lazy allocation for `assign_attributes` and `_assign_attributes`
  Tweak contributing_to_ruby_on_rails.md [ci skip]
  Clarify the difference between (old) `spec_name` and `connection_specification_name`
  Remove duplicate part from deprecation warning
  Fix deprecation warnings in connection_handlers_sharding_db_test.rb
  Fixup CHANGELOGs [ci skip]
  `reset_column_information` does not reset @predicate_builder
  Simplify FixtureResolver to reuse filtering logic
  Mostly remove bad test
  Use type attribute in ActionView::Helpers::JavaScriptHelper#javascript_tag example
  Update some references to finder options [ci skip]
2020-02-27 16:48:15 -08:00
Aaron Patterson
5f596e299e
Add a regression test that ActionText caught
ActionText is using ActionView in a way that ActionView doesn't have in
it's test suite.  This is just a regression test to hit that same use
case.
2020-02-27 16:47:22 -08:00
Aaron Patterson
4a4a8be064
make the cops happy 2020-02-27 15:38:20 -08:00
Aaron Patterson
8d539bde7b
Move around local variable derivation
This reduces object allocations in collection rendering
2020-02-27 15:01:52 -08:00
Aaron Patterson
374c1b2940
fix require 2020-02-27 14:12:09 -08:00
Aaron Patterson
78a28b7c47
always lookup template from path cache 2020-02-27 13:52:53 -08:00
Aaron Patterson
7c0dea18ce
Reduce iterations for non-homogeneous collections
We only need to iterate over the paths twice (this was doing it 3 times)
2020-02-27 13:20:34 -08:00
Aaron Patterson
266e34973e
Remove conditional
Only one case can possibly be missing a partial.  We can move the cache
check to that branch and eliminate the conditional
2020-02-27 13:15:56 -08:00
Aaron Patterson
76ea105ca1
remove collection ivar 2020-02-27 13:14:09 -08:00
Aaron Patterson
a85494dc0c
Move renderers in to their own files
We don't need to keep all of these in the partial renderer file
2020-02-27 12:55:04 -08:00
Aaron Patterson
665a355ed8
We don't need this private method 2020-02-27 12:50:02 -08:00
Aaron Patterson
dbd8860096
move object specific stuff in to the object processing code 2020-02-27 12:49:53 -08:00
Ryuta Kamizono
4d641a3363 Fix helper_method in ActionView::TestCase to allow keyword arguments 2020-02-28 04:46:05 +09:00
Aaron Patterson
f0429dbc30
Make extracting details cheaper
Details are only used if the user specifies a format or local, etc when
rendering a template.  This is a fairly uncommon thing to do, so lets
make it cheaper when there are no details specified
2020-02-26 17:14:37 -08:00
Aaron Patterson
2105fec017
Merging path prefixes is only done in object / collection rendering 2020-02-26 17:14:18 -08:00
Aaron Patterson
51f50a923e
path ivar is not required 2020-02-26 16:44:35 -08:00
Aaron Patterson
17fb6f0503
Move partial_path to ObjectRendering
Partial paths are only required for deriving template info for rendering
objects, which is only the case for the object renderer and the
collection renderer
2020-02-26 16:42:42 -08:00
Aaron Patterson
7210adb7ec
move locals and details ivar set in to initialize 2020-02-26 16:35:03 -08:00
Aaron Patterson
ef6e03d5b1
Move options ivar assignment in to the superclass 2020-02-26 16:33:27 -08:00
Aaron Patterson
f3dfd28821
remove extra ivar set 2020-02-26 16:19:19 -08:00
Aaron Patterson
f8f2f9ce32
remove the as_variable method 2020-02-26 16:17:49 -08:00
Aaron Patterson
f0a1548433
as: doesn't make sense without an object parameter
The local variable name in `as:` may not be a valid local variable name,
but if there is no object specified to be assigned to the parameter,
then why supply the `as:`?  This commit adds an object for the as param
2020-02-26 16:13:12 -08:00
Aaron Patterson
9187f7482c
partial renderer is specialized for rendering partials now 2020-02-26 15:57:59 -08:00
Aaron Patterson
feec68436c
remove has_object ivar 2020-02-26 15:39:57 -08:00
Aaron Patterson
8b6c5850a5
introduce an object renderer 2020-02-26 15:37:45 -08:00
Aaron Patterson
844568c231
remove at ivar again 2020-02-26 15:06:29 -08:00
Aaron Patterson
10f7201fc5
remove more collection references from the superclass 2020-02-26 15:04:18 -08:00
Aaron Patterson
974ddb035c
remove collection references from the superclass 2020-02-26 14:59:33 -08:00
Aaron Patterson
0c1fbc7e04
collection rendering has its own class 2020-02-26 14:51:31 -08:00
Aaron Patterson
0c1d14a810
a collection is never rendered with an object 2020-02-26 08:34:03 -08:00
Aaron Patterson
6539657a3c
pull iterator allocation in to a factory method 2020-02-26 08:18:47 -08:00
Aaron Patterson
347094856c
Only iterate over collections once when a path is provided
We'll later reuse this object to speed up the case when a relation is
passed in.
2020-02-25 16:07:36 -08:00
Aaron Patterson
638cc381b1
rely less on the collection ivar 2020-02-25 15:17:05 -08:00
John Hawthorn
22d9b3e83e
Merge pull request #38569 from jhawthorn/simplify_fixture_resolver
Simplify fixture resolver
2020-02-25 14:54:17 -08:00
Aaron Patterson
5fa2c69e4b
Don't to_a things when we don't need to.
If the partial renderer is passed a relation or collection proxy, it
will be good for us to resolve that relation or collection proxy as late
as possible.
2020-02-25 14:42:52 -08:00
Aaron Patterson
c52fa675b8
Find the layout earlier
Remove duplication in finding a layout.  Remove `@as` ivar.
2020-02-25 14:12:38 -08:00
Aaron Patterson
67b1a7942e
remove useless conditional 2020-02-25 13:52:45 -08:00
Aaron Patterson
7a9c90184a
variable ivar is not needed anymore 2020-02-25 13:42:05 -08:00
Aaron Patterson
99d74cac99
Don't rely on the collection ivar
We're going to turn this in to a more complex iterator
2020-02-25 13:33:41 -08:00
Aaron Patterson
64b3bcb0b9
block does not need to be an ivar 2020-02-25 10:26:43 -08:00
Aaron Patterson
867c4c2e60
collection with/without template are the same 2020-02-25 10:25:41 -08:00
Aaron Patterson
96f89fbf5d
collection with/without template are more similar 2020-02-25 10:05:42 -08:00
Aaron Patterson
dc1633090e
extract template keys to a method 2020-02-24 19:43:28 -08:00
Aaron Patterson
7e872091e1
pull template keys up 2020-02-24 19:17:38 -08:00
John Hawthorn
c3c1c32f4b Simplify FixtureResolver to reuse filtering logic
Previously FixtureResolver had a copy-pasted version of the filtering
already done by OptimizedFileSystemResolver. This PR replaces this by
extracting the two places actual filesystem operations into separate
methods and overriding those.

It would be nice to not rely on overriding methods at all, and to
extract the actual filtering into a separate, reusable class, but I
don't want to do that until some other changes are made to the
filtering.

This should also make FixtureResolver much more accurate to
OptimizedFileSystemResolver, by also creating and caching the
UnboundTemplate classes, which de-duplicate templates.
2020-02-24 16:22:58 -08:00
John Hawthorn
a9e455f484 Mostly remove bad test
This test was attempting to test how cache keys work by modifying the
templates and seeing when that cache was fresh. This doesn't actually
work for real Resolvers, only FixtureResolver, and isn't desirable. We
absolutely want to share templates if they resolve to the same file.

Instead, this simplifies the test to only check that we get the correct
template for the locale we request.
2020-02-24 16:20:33 -08:00
Gannon McGibbon
eaa33bbdff Use type attribute in ActionView::Helpers::JavaScriptHelper#javascript_tag example 2020-02-24 18:04:29 -05:00
Steve Thomas
ddcc3212c0 Update boolean attributes for actionview tag helper 2020-02-24 10:23:30 -05:00
Eugene Kenny
9e40348645 Enable HashTransformKeys and HashTransformValues cops
Followup to 88fe76e69328d38942130e16fb65f4aa1b5d1a6b.

These are new in RuboCop 0.80.0, and enforce a style we already prefer
for performance reasons (see df81f2e5f5df46c9c1db27530bbd301b6e23c4a7).
2020-02-20 22:37:32 +00:00
Joel Hawksley
05a2a939f0 Remove validations from example components
We're moving away from using validations in our
component framework, and feel that it's better
to avoid prescribing their usage in these
example classes, which exist to serve as example
objects that are compatible with the render_in
API.
2020-02-20 09:48:25 -07:00
aminamos
7bb0706f2c update from PR #36222 2020-02-12 13:31:43 -05:00
Stefan Wrobel
8877b5ff16
Fix translate method with default: nil
```ruby
    I18n.translate('missing.translation', default: nil)
    # => nil
    helper.translate('missing.translation', default: nil)
    # Before
    # => "<span class=\"translation_missing\" title=\"translation missing: en.missing.translation\">Translation</span>"
    # After
    # => nil
    ```
2020-02-09 23:22:00 +01:00
Ryuta Kamizono
051e349041 Prefer faster str.start_with? over str.first ==
```ruby
str = "abc"

Benchmark.ips do |x|
  x.report("start_with?") { str.start_with?("a") }
  x.report("first ==")    { str.first == "a" }
end
```

```
Warming up --------------------------------------
         start_with?   282.381k i/100ms
            first ==   207.305k i/100ms
Calculating -------------------------------------
         start_with?     10.239M (± 2.2%) i/s -     51.393M in   5.022151s
            first ==      4.593M (± 4.5%) i/s -     23.011M in   5.021434s
```
2020-02-05 19:15:33 +09:00
Ryuta Kamizono
b803ed012c Make localize helper takes keyword arguments the same with I18n.localize 2020-02-05 18:49:44 +09:00
Ryuta Kamizono
6c02fee08f Make translate helper takes keyword arguments the same with I18n.translate 2020-02-05 18:04:27 +09:00
Ryuta Kamizono
5d2789b11b Avoid extra Array allocation for build_tag_values 2020-01-16 08:25:38 +09:00
Iago Pimenta
e7c3eb11e0 Use default order of PathResolver::EXTENSIONS for sort templates 2020-01-09 12:01:41 -08:00
John Hawthorn
cd0fbaea01 Define fake_zones on AS::TimeZone, not singleton
Previously this was incorrectly defining this attribute on the singleton
class, which would end up actually using the class variable from Module.
2020-01-04 17:50:59 -08:00
Ryuta Kamizono
785427b88c Merge pull request #38132
Closes #38132
2020-01-02 17:29:00 +09:00
Josef Šimánek
64f3bd0a8d
Use travel_to to in date_helper_test.rb. 2020-01-02 02:11:33 +01:00
Abhay Nikam
d8beb77252 Bump license years from 2019 to 2020 [ci skip] 2020-01-01 15:10:31 +05:30
Rafael França
4fbb393b25
Merge pull request #35023 from hahmed/deprecate-global-rails-command-docs
Remove reference to global rails command in the docs
2019-12-27 16:39:55 -03:00
Haroon Ahmed
db1ae8cbb4 remove reference to global rails command and replace with bin/rails 2019-12-27 19:32:37 +00:00
Rafael Mendonça França
855cb4bef2
Call method outside the loop
We only need to call this method once.
2019-12-27 15:13:44 -03:00
Ben Ubois
2bb7dbf75d Improve escape_javascript performance. 2019-12-22 23:52:37 +01:00
Kasper Timm Hansen
6047301063
Merge pull request #38059 from eugeneius/source_extract_encode_template
Encode template source before extracting lines
2019-12-22 08:56:29 +01:00
John Hawthorn
5579871687 Use ActionDispatch mimes in asset_tag_helper_test
We need a more complete understanding of mime types for the asset tags
to render properly, so we need to load this rather than just the stubs
included by actionview by default.

This fixes running these tests in isolation.
2019-12-21 03:38:39 -08:00
Eugene Kenny
d7b015a167 Encode template source before extracting lines
Before 2169bd3d2a9d2f331a5dd6e41d9d638e0da6117c, a template's source was
encoded in place when it was compiled, and the `source_extract` method
could rely on `Template#source` to return a properly encoded string.

Now that `Template#source` always returns a new copy of the template
source with no encoding, `source_extract` should call `encode!` itself.
2019-12-21 07:30:52 +00:00
Ryuta Kamizono
b3da023081 Add ruby2_keywords for delegating to fields helper 2019-12-21 02:44:26 +09:00
Rafael França
e36d4a0381
Merge pull request #38026 from Edouard-chin/ec-av-base-loadorder
Don't require "action_view/base" in action pack:
2019-12-19 13:40:56 -03:00
Edouard CHIN
88ee52f9d9 Don't require "action_view/base" in action pack:
- ### Problem

  ActionPack requires "action_view/base" at boot time, this
  causes a variety of issue that I described in detail in #38024.

  There is no real reason to require av/base in the
  ActionDispatch::Debugexceptions class.

  ### Solution

  Like any other components (such as ActiveRecord, ActiveJob...),
  ActionView::Base shouldn't be loaded at boot time.

  Here are the two main changes needed for this:

  1) Actionview has a special initializer that needs to run
     before the app is fully booted (adding a executor needs to be done
     before application is done booting)
  63ec70e700/actionview/lib/action_view/railtie.rb (L81-L84)

     That initializer used a lazy load hooks but we can't do that anymore
     because Action::Base view won't be triggered during booting process.
     When it will get triggered, (presumably on the first request),
     it's too late to add an executor.

  ------------------------------------------------

  2) Compare to other components, ActionView doesn't use `Base` for
     configuration flag. A lot of flags ares instead set on modules
     (FormHelper, FormTagHelper).
     The problem is that those module depends on AV::Base to be
     loaded, as otherwise configuration set by the user aren't applied.
     (Since the lazy load hooks hasn't been triggered)
     63ec70e700/actionview/lib/action_view/railtie.rb (L66-L69)

     We shouldn't wait for AB::Base to be loaded in order to set these
     configuration. However, we need to do it inside an
     `after_initialize` block in order to let application
     set it to the value they want.

  Closes #28538

  Co-authored-by: betesh <iybetesh@gmail.com>"
2019-12-19 17:28:24 +01:00
Rafael França
8619a76be8
Merge pull request #28902 from voxik/fix-inspect
Prevent negative IDs in output of #inspect.
2019-12-19 13:20:45 -03:00
Rafael França
afdee462a8
Merge pull request #36147 from pustomytnyk/patch-1
Fix handling of undefined year in DateTimeSelector
2019-12-18 12:24:16 -03:00
Rafael Mendonça França
7c1bf1a474
Merge pull request #25214 from maclover7/jm-av-tests
Cleanup Action View `abstract_unit`
2019-12-18 12:23:11 -03:00
Roman Sokhan
8251651a0d Fix handling of undefined year in DateTimeSelector 2019-12-18 16:56:09 +02:00
Rafael França
f741f56da3
Merge pull request #37865 from hectorbus/number-to-currency-negative-zero-fix
number_to_currency negative zero fix
2019-12-17 12:30:57 -03:00
Ryuta Kamizono
0c2bb3485c
Merge pull request #37995 from abhaynikam/37918-fix-typo-in-class_names-helper-documentation
Fixed typo in the class_names helper documentation
2019-12-17 15:04:50 +09:00
Eugene Kenny
ee525ff663 Load framework test files in deterministic order
`Dir.glob` doesn't guarantee the order of its results:

https://ruby-doc.org/core-2.6.5/Dir.html#method-c-glob

> Case sensitivity depends on your system (File::FNM_CASEFOLD is
> ignored), as does the order in which the results are returned.

Minitest stores a list of all test cases in the order that they were
defined; it shuffles them before they're run, but doesn't sort them:

https://github.com/seattlerb/minitest/blob/v5.13.0/lib/minitest.rb#L1048
https://github.com/seattlerb/minitest/blob/v5.13.0/lib/minitest.rb#L156

This means that the order in which framework tests run is platform
dependent, and running a test command that failed in CI locally won't
necessarily reproduce the error, even when the same seed is provided.

`Rake::FileList` resolves glob patterns to a sorted list of files:

https://github.com/ruby/rake/blob/v13.0.1/lib/rake/file_list.rb#L408

By using `Rake::FileList` instead of `Dir.glob`, framework tests will
always run in the same order when given the same seed, and reproducing
order dependent CI failures will be easier.
2019-12-16 16:55:06 +00:00
Abhay Nikam
2cd84ad745 Fixed typo in the class_names helper documentation and added a spec covering the scenario 2019-12-16 13:48:19 +05:30
Kasper Timm Hansen
2bcf24795b
Merge pull request #37928 from CGA1123/fix-race-in-action-view
Make ActionView::LookupContext::DetailsKey thread-safe
2019-12-12 22:47:30 +01:00
Joel Hawksley
e1545682eb
Add changelog entry for https://github.com/rails/rails/pull/37918
Per request from @bogdanvlviv.
2019-12-11 09:20:38 -07:00
Eileen M. Uchitelle
774e77c2cc
Merge pull request #37918 from joelhawksley/class_names_helper
Introduce class_names helper
2019-12-10 09:27:37 -05:00
Eileen M. Uchitelle
e36097a950
Merge pull request #37919 from joelhawksley/controller-render-in
Render objects that respond_to render_in in controllers
2019-12-10 09:18:26 -05:00
Joel Hawksley
20a83f52d7
Render objects that respond_to render_in in controllers
In https://github.com/rails/rails/pull/36388,
we supported passing objects that `respond_to` `render_in`
to `render`, but _only_ in views.

This change does the same for controllers, as Rails
generally gives the expectation that `render` behaves
the same in both contexts.

Co-authored-by: Aaron Patterson <tenderlove@github.com>
2019-12-09 16:43:18 -07:00
Joel Hawksley
f24734a7e1
Introduce class_names helper
As a follow-up to https://github.com/rails/rails/pull/37872,
this change introduces a class_names view helper
to make it easier to conditionally apply class names
in views.

Before:
<div class="<%= item.for_sale? ? 'active' : '' %>">

After:
<div class="<%= class_names(active: item.for_sale?) %>">

We've been using this helper in the GitHub monolith
since 2016.

Co-authored-by: Aaron Patterson <tenderlove@github.com>
2019-12-09 16:41:18 -07:00
Edouard CHIN
95bc8d0a23 Fix input value not properly applied:
- #37872 introduced a regression and you can't do

  ```html.erb
    hidden_field_tag('token', value: [1, 2, 3])
  ```

  This will result in a `<input type="hidden" value=""`>.

  I chose `hidden_field_tag` and the `value` attribute as an example
  but this issue applies to any tag helper and any attributes.

  https://github.com/rails/rails/pull/37872#issuecomment-561806468
  mention that the feature should only apply for "class" attribute.

  This commit fix original intent of #37872
2019-12-09 22:54:25 +01:00
Rafael Mendonça França
e67fdc5aeb
Revert "Merge pull request #37504 from utilum/no_implicit_conversion_of_nil"
This reverts commit 4e105385d046e2aeab16955943df97c5eefa3a6f, reversing
changes made to 62b43839098bbbbfc4be789128d33dc0612f1ab3.

The change in Ruby that made those changes required was reverted in
8852fa8760
2019-12-09 11:50:39 -03:00
Santiago Bartesaghi
8872ec431a
perform_caching config affects collection caching 2019-12-05 21:46:02 +01:00
Joel Hawksley
54f418d96d
appease rubocop 2019-12-03 11:45:51 -07:00
Joel Hawksley
f508d4da4d
Merge branch 'master' into content-tag-hash-class-conditional 2019-12-03 11:32:58 -07:00
Joel Hawksley
f1c63d8673
Add support for conditional values to TagBuilder
Adds support for conditional values to TagBuilder,
extracting logic we use in the GitHub application,
inspired by https://github.com/JedWatson/classnames.

It’s common practice to conditionally apply CSS classes
in Rails views. This can lead to messy string interpolation,
often using ternaries:

```ruby
content_tag(
  "My username",
  class: "always #{'sometimes' if current_user.special?} another"
)
```

By adding support for hashes to TagBuilder, we can instead write the following:

```ruby
content_tag(
  "My username",
  class: ["always", "another", { 'sometimes' => current_user.special? }]
)
```

cc @JedWatson
2019-12-03 11:30:38 -07:00
Hector Bustillos
92fea7a574 number_to_currency negative zero fix 2019-12-02 23:18:26 -07:00
Michael MacDonald
2863619b94
Fix minor typo in pattern example for number_to_phone [ci skip]
There is an extra closing parenthesis on the last example for `number_to_phone` which causes it to be invalid
2019-11-28 22:08:39 +11:00
Ryuta Kamizono
d558febe32 Auto-correct rubocop offences 2019-11-24 09:54:47 +09:00
Ryuta Kamizono
214f439343 Fixup CHANGELOGs [ci skip] 2019-11-24 09:20:00 +09:00
BelenRemedi
4bf9e49ec4 show consitency in cache key and avoid getting into implementation details 2019-11-22 10:12:00 -03:00
Tatsuya Hoshino
41f0fb8c6e Remove needless require "pp"
In Ruby 2.5 and later, `Kernel#pp` is automatically loaded.

https://bugs.ruby-lang.org/issues/14123

This changes remove the needless `require "pp"`.
2019-11-06 22:50:53 +09:00
Artin Boghosian
ec737fb846
Use singular, instance, in deprecation warning. 2019-11-04 13:45:46 -08:00
Rafael Mendonça França
86dd7d1621
No need to break the line 2019-11-04 15:24:40 -05:00
utilum
2ca6830831 TypeError Regexp#match?(nil) in Ruby Head
Aa of ruby/ruby@2a22a6b2d8 calling
`Regexp#match?(nil)` raises an exception.

[utilum, eregon, eugeneius]
2019-11-03 09:26:46 +02:00
Kasper Timm Hansen
d2e8b839d2
Merge pull request #37561 from SinanMujan/fix_docs_actionview
[ci skip] Small fixes in ActionView documentation.
2019-10-27 08:31:23 -05:00
John Hawthorn
82f9d7c8b6
Merge pull request #37445 from jhawthorn/optimize_content_tag
Make content_tag a bit faster
2019-10-25 13:13:03 -07:00
sinanmujan
f66946b11a [ci skip] Small fixes in ActionView documentation. 2019-10-25 09:02:26 +02:00
Orien Madgwick
493edf044f Add bug tracker/documentation/mailing list URIs to the gemspecs 2019-10-11 20:47:19 -04:00
John Hawthorn
25ed6627dd Convert two hash lookups into one 2019-10-11 13:52:51 -07:00
John Hawthorn
a2720dd053 Avoid extra allocations when don't need escaping 2019-10-11 13:35:11 -07:00
Takayuki Nakata
4871f1f8d1 Remove unused requires
`remove_method` were removed at 661fd98aad and 737b718ea0
2019-10-07 10:03:46 +09:00
Kasper Timm Hansen
eca6c273fe
[ci skip] switch eg. to proper e.g. 2019-10-07 02:18:36 +02:00