Commit Graph

7771 Commits

Author SHA1 Message Date
Richard Schneeman 4dbb75bd6e
Merge pull request #33936 from schneems/schneems/cache-micro-optimizations
Decrease memory allocations in cache.rb
2018-10-04 07:55:59 +08:00
yuuji.yaginuma c55fc43b3f Don't use deprecated `LoggerSilence` 2018-10-04 08:23:49 +09:00
Rafael França ebf98df9fb
Merge pull request #34055 from Edouard-chin/ec-logger-fix
Fix the LoggerSilence to work as described:
2018-10-03 16:45:53 -04:00
Akira Matsuda b2bc4369a3 Bring config_accessor's API document back to its life
the document has been disappeared since the method became private at c2bfe6cbc8
2018-10-03 21:42:55 +09:00
Akira Matsuda 370537de05 ⚠️ assigned but unused variable - logger 2018-10-03 21:38:57 +09:00
Edouard CHIN 05ad44eb89 Fix the LoggerSilence to work as described:
- Following the Rails guide which state that a logger needs to include
  the `ActiveSupport::LoggerSilence` as well as
  `ActiveSupport::LoggerThreadSafe` modules isn't enough and won't
  work.

  Here is a test cases with 3 tests that all fails
  https://gist.github.com/Edouard-chin/4a72930c2b1eafbbd72a80c66f102010

  The problems are the following:

  1) The logger needs to call `after_initialize` in order to setup
  some instance variables.
  2) The silence doesn't actually work because the bare ruby Logger
  `add` method checks for the instance variable `@logger`. We need to
  override the `add` (like we used to in the ActiveSupport::Logger
  class).
  3) Calling `debug?` `info?` etc... doesn't work as the bare ruby
  methods will check for the instance variable. Again we need to
  override this methods (like we used to in the ActiveSupport::Logger
  class)

  The LoggerSilence won't work without LoggerThreadSafe, but the later
  is not public API, the user shouldn't have to include it so I
  modified to include it automatically.
  Same for the `after_initialize` method. I find unuintitive to have
  to call it directly. I modified to instance the variables when the
  module get included.
2018-10-02 17:17:23 -04:00
Rafael Mendonça França 92fece96da
Merge pull request #34051 from gmcgibbon/module_parent_method_rename
Prefix Module#parent, Module#parents, and Module#parent_name with module
2018-10-02 16:04:23 -04:00
Gannon McGibbon c401c43850 Fix call sites 2018-10-02 15:31:29 -04:00
Edouard CHIN 783f86822b Deprecate the `LoggerSilence` constant:
- I found this weird that the LoggerSilence wasn't using the
  `ActiveSupport` namespace (AFAIK all other classes have it).

  This PR deprecate the use of `LoggerSilence` for
  `ActiveSupport::LoggerSilence` instead.
2018-10-02 12:59:04 -04:00
Gannon McGibbon 004fda3568 Prefix Module#parent, Module#parents, and Module#parent_name with module 2018-10-02 12:51:35 -04:00
Rafael França cf608ee34d
Merge pull request #33058 from gmcgibbon/string_first_last_negative_deprecation
Add deprecation warning when String#first and String#last receive neg…
2018-10-02 11:05:40 -04:00
Markus Reiter c08272ac24 Ensure correct permission when `tmpdir` is the same as `dirname`. 2018-10-02 16:40:39 +02:00
Sharang Dashputre 3c4b729f48 Fix spellings for 'unmarshall(ing/ed)' & 'marshall(ing/ed)' 2018-10-02 13:55:39 +05:30
Rune Philosof 2c871ebc64
Make it easier to find abort documentation
Make sure how to abort is documented on https://api.rubyonrails.org/classes/ActiveSupport/Callbacks.html
2018-10-01 11:49:07 +02:00
Ryuta Kamizono b13a5cb83e
Merge pull request #32031 from yahonda/remove_redundant_freeze
Add `Style/RedundantFreeze` to remove redudant `.freeze`
2018-10-01 10:08:51 +09:00
Lachlan Sylvester 5f6a906094 Require the except hash extension before trying to alias it 2018-10-01 08:08:08 +10:00
Yasuo Honda aa3dcabd87 Add `Style/RedundantFreeze` to remove redudant `.freeze`
Since Rails 6.0 will support Ruby 2.4.1 or higher
`# frozen_string_literal: true` magic comment is enough to make string object frozen.
This magic comment is enabled by `Style/FrozenStringLiteralComment` cop.

* Exclude these files not to auto correct false positive `Regexp#freeze`
 - 'actionpack/lib/action_dispatch/journey/router/utils.rb'
 - 'activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb'

It has been fixed by https://github.com/rubocop-hq/rubocop/pull/6333
Once the newer version of RuboCop released and available at Code Climate these exclude entries should be removed.

* Replace `String#freeze` with `String#-@` manually if explicit frozen string objects are required

 - 'actionpack/test/controller/test_case_test.rb'
 - 'activemodel/test/cases/type/string_test.rb'
 - 'activesupport/lib/active_support/core_ext/string/strip.rb'
 - 'activesupport/test/core_ext/string_ext_test.rb'
 - 'railties/test/generators/actions_test.rb'
2018-09-29 07:18:44 +00:00
Gannon McGibbon ec9a89cb8b Add deprecation warning when String#first and String#last receive negative integers
[Gannon McGibbon + Eric Turner]
2018-09-28 14:29:46 -04:00
Abraham Chan b2ea831073 Fix HashWithIndifferentAccess#without bug 2018-09-28 18:28:56 +10:00
Edouard CHIN 874cff399c LoggerSilence doesn't require concurrent:
- LoggerThreadSafeLevel does nowaday since 2518bda97c
2018-09-28 02:09:57 -04:00
Janosch Müller 47f2686148 Handle more unsafe String methods (#33990)
* Handle more unsafe String methods

* Fix codeclimate issue

* Revert stylistic change

[Janosch Müller + Rafael Mendonça França]
2018-09-27 20:50:21 -04:00
Rafael Mendonça França f679933daa
Change the empty block style to have space inside of the block 2018-09-25 13:19:35 -04:00
Kasper Timm Hansen 22dc2b3db8
Merge pull request #33949 from sjain1107/no-private-def
Remove private def
2018-09-23 19:39:15 +02:00
Sakshi Jain 0fe2bb816f Remove private def 2018-09-23 21:27:44 +05:30
yuuji.yaginuma 1b86d90136 Enable `Performance/UnfreezeString` cop
In Ruby 2.3 or later, `String#+@` is available and `+@` is faster than `dup`.

```ruby
# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  gem "benchmark-ips"
end

Benchmark.ips do |x|
  x.report('+@') { +"" }
  x.report('dup') { "".dup }
  x.compare!
end
```

```
$ ruby -v benchmark.rb
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
Warming up --------------------------------------
                  +@   282.289k i/100ms
                 dup   187.638k i/100ms
Calculating -------------------------------------
                  +@      6.775M (± 3.6%) i/s -     33.875M in   5.006253s
                 dup      3.320M (± 2.2%) i/s -     16.700M in   5.032125s

Comparison:
                  +@:  6775299.3 i/s
                 dup:  3320400.7 i/s - 2.04x  slower

```
2018-09-23 08:56:55 +09:00
schneems 6da99b4e99 Decrease memory allocations in cache.rb
The `merged_options` method is private and the output is never mutated.
Using this info we can get rid of the `dup` behavior. We can also
eliminate the `merge` call in the case where all the options being merged are the same.

Returned results are frozen as an extra layer of protection against
mutation.

Before

```
Total allocated: 741749 bytes (6642 objects)
```

After

```
Total allocated: 734039 bytes (6648 objects)
```

Diff

```
(741749 - 734039) / 741749.0 => ~ 1.0 %
```

If you don't feel comfortable modifying this method, we could rename it
and only use it internally.
2018-09-21 17:33:17 -05:00
schneems 3424bd83d6 Switch to supports_cache_versioning? check to a class method
- Moving the `supports_cache_versioning?` check to a class method. 
- Shorten the method doc. 
- Expand on the error message.
2018-09-20 20:40:31 -05:00
schneems 135d3e15b7 [close #33907] Error when using "recyclable" cache keys with a store that does not support it
If you are using the "in cache versioning" also known as "recyclable cache keys" the cache store must be aware of this scheme, otherwise you will generate cache entries that never invalidate.

This PR adds a check to the initialization process to ensure that if recyclable cache keys are being used via 

```
config.active_record.cache_versioning = true
```

Then the cache store needs to show that it supports this versioning scheme. Cache stores can let Rails know that they support this scheme by adding a method `supports_in_cache_versioning?` and returning true.
2018-09-20 15:31:38 -05:00
Xavier Noria ec88cd626d
Merge pull request #33800 from aeroastro/feature/doc-change-for-blank
Improve API document on Object#blank?
2018-09-13 22:24:43 +02:00
Takumasa Ochi 2a82c47501
Revert falsey with example reordered 2018-09-14 02:41:46 +09:00
rigani 66bfb37f50 Faster multiple_of? method 2018-09-12 18:45:47 +09:00
Rafael Mendonça França e09c55dc8e
Merge pull request #27792 from tjoyal/sandbox-tagged-logging
TaggedLogging to return a new logger instance
2018-09-11 19:33:59 -04:00
Xavier Noria f589e20b0a use "minitest" consistently
The name of the minitest library is spelled that way: regular font, and
lowercase. Lowercase is used even at the beginning of sentences, see

    http://docs.seattlerb.org/minitest/

I double-checked this with @zenspider too (thanks!).
2018-09-11 23:57:25 +02:00
Xavier Noria e7fc2afb21 Oxford comma [ci skip]
Followup to a recently merged PR, too minor and detailed to require a
modification to the contributed patch.
2018-09-10 23:51:26 +02:00
ryanwhocodes 36e6571a40 Add #unfreeze_time to ActiveSupport::Testing::TimeHelpers 2018-09-10 22:32:41 +01:00
Xavier Noria 5f35c60f84 reflect c03bba4 in CHANGELOGs 2018-09-08 09:50:05 +02:00
Xavier Noria c03bba4f1f trace autoloads, and document hints for troubleshooting
Closes #32885.
2018-09-07 23:32:54 +02:00
Ryuta Kamizono 736edb9828 Formatting CHANGELOGs [ci skip]
Fixing code block rendering, indentation, backticks, etc.
2018-09-07 07:59:19 +09:00
Aaron Patterson b31ae3131a
Merge pull request #33808 from itsbagpack/fix-access-safety-buffer-slice
Maintain html_safe? on sliced HTML safe strings
2018-09-06 15:00:05 -07:00
Yumin Wong 1d42a661d8 Update CHANGELOG for SafetyBuffer slice access
Co-authored-by: no-itsbackpack <no-itsbackpack@github.com>
2018-09-06 15:17:18 -05:00
Olivier 70e3d1ea9d
Fix typo in i18n_railtie.rb 2018-09-06 15:09:24 -04:00
Richard Schneeman 4b010b0815
Merge pull request #33805 from schneems/schneems/faster-file-store
Faster File Store
2018-09-06 14:49:26 -04:00
Rafael França 62a0c30754
Merge pull request #33574 from lsylvester/change-i18n-defaults-behaviour-to-match-i18n-1.1.0
update I18n fallbacks configuration to be compatible with i18n 1.1.0
2018-09-06 14:38:26 -04:00
Yumin Wong 0a1567793b Use assert_predicate instead
Co-authored-by: no-itsbackpack <no-itsbackpack@github.com>
2018-09-06 12:48:50 -05:00
schneems 8eb3cd8e56 Faster File Store
Memory before 1826584.8	 memory after: 1797795.6 difference: 1.58% memory (speed) savings.

When the key is not longer than the limit we can avoid allocating two strings and an array.
2018-09-06 10:13:42 -05:00
Eileen Uchitelle 38f074f0a8 Ensure we always cleanup the databases
This commit moves the `run_cleanup` hook into an `ensure` block so we
make sure to cleanup the databases even if an exception is raised while
running the parallel tests.
2018-09-05 14:43:14 -04:00
Takumasa Ochi d309737928 Improve API document on Object#blank?
* Introduce `falsey` to represent both `nil` and `false`.
* Keep consistent order between abstract description and examples.
2018-09-06 02:13:39 +09:00
Yumin Wong 3f5bd11ed6 SafeBuffer should maintain safety upon getting a slice via a range if original buffer was safe.
Co-Authored-By: no-itsbackpack <no-itsbackpack@github.com>
2018-08-31 11:46:09 -05:00
yuuji.yaginuma 12fadea8ae Remove redundant `travel_back`
Since #29860, `travel_back` automatically called at the end of the test.
2018-08-31 16:19:58 +09:00
Sean Griffin 0f462da85d 20% faster `try`
Following up on #33747, this takes things a step further by pulling out
the method name from the arguments array, letting us skip an allocation
in the case where there are no arguments -- notably, this also no longer
*requires* the splat to be an array, allowing us to benefit from
optimizations in Jruby (and maybe MRI in the future) of skipping the
array allocation entirely.

Benchmark results:

```
Warming up --------------------------------------
                 old   179.987k i/100ms
                 new   199.201k i/100ms
Calculating -------------------------------------
                 old      3.029M (± 1.6%) i/s -     15.299M in   5.052417s
                 new      3.657M (± 1.2%) i/s -     18.326M in   5.012648s

Comparison:
                 new:  3656620.7 i/s
                 old:  3028848.3 i/s - 1.21x  slower
```
2018-08-29 12:42:01 -06:00
Richard Schneeman 96d7504da9
Merge pull request #33747 from schneems/schneems/faster-try
32% Faster Object#try
2018-08-29 09:10:49 -07:00
schneems ba7d1265e3 32% Faster Object#try
Here’s the micro benchmark:

```ruby
module ActiveSupport
  module NewTryable #:nodoc:
    def try(*a, &b)
      return unless a.empty? || respond_to?(a.first)
      return public_send(*a, &b) unless a.empty?

      return nil unless block_given?
      return instance_eval(&b) if b.arity == 0
      yield self
    end

    def try!(*a, &b)
      return public_send(*a, &b) if !a.empty?
      return nil unless block_given?
      return instance_eval(&b) if b.arity == 0
      yield self
    end
  end
end


module ActiveSupport
  module OldTryable #:nodoc:
    def try(*a, &b)
      try!(*a, &b) if a.empty? || respond_to?(a.first)
    end

    def try!(*a, &b)
      if a.empty? && block_given?
        if b.arity == 0
          instance_eval(&b)
        else
          yield self
        end
      else
        public_send(*a, &b)
      end
    end
  end
end

class FooNew
  include ActiveSupport::NewTryable

  def foo
  end
end

class FooOld
  include ActiveSupport::OldTryable

  def foo
  end
end 


foo_new = FooNew.new
foo_old = FooOld.new

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report("old") { foo_old.try(:foo) }
  x.report("new") { foo_new.try(:foo) }
  x.compare!
end

# Warming up --------------------------------------
#                  old   144.178k i/100ms
#                  new   172.371k i/100ms
# Calculating -------------------------------------
#                  old      2.181M (± 8.0%) i/s -     10.813M in   5.001419s
#                  new      2.889M (± 7.7%) i/s -     14.479M in   5.051760s

# Comparison:
#                  new:  2888691.7 i/s
#                  old:  2180740.7 i/s - 1.32x  slower
```

Also reduces memory. On https://www.codetriage.com i’m seeing 1.5% fewer object allocations per request (in object count).

Before:

Total allocated: 1014475 bytes (8525 objects)

After:

Total allocated: 1015499 bytes (8389 objects)
2018-08-29 10:03:48 -05:00
Rob Race 018ff582a5 Update the comments for TimeWithZone subtraction (#33721)
* Update the comments for TimeWithZone subtraction

While reading the description/documentation comments for the subtraction method, it was confusing. While in practical usage, the returned values make sense. It seems as though the explanation could be a bit clearer.

* Removed erroneous closing parenthesis

[ci skip]

[Rob Race + Ryuta Kamizono]
2018-08-28 17:32:18 +09:00
Lachlan Sylvester 66614f6b67 update I18n fallbacks configuration to be compatible with i18n 1.1.0 2018-08-23 06:56:42 +10:00
Kasper Timm Hansen 9136bb77a7
Merge pull request #33162 from utilum/stop_using_mocha
Stop using Mocha
2018-08-22 18:20:25 +02:00
Fabian Schwahn ec6089995d Improve documentation of Procs as :if / :unless options for callbacks 2018-08-20 11:44:31 +02:00
Ryuta Kamizono 103b02f152
Merge pull request #31132 from emaxi/feature/add-missing-documentation-option-to-number-to-currency
Add missing documentation option to number_to_currency

[ci skip]
2018-08-20 10:49:54 +09:00
yuuji.yaginuma 0193b89be6 Remove unused requires 2018-08-17 12:51:14 +09:00
Vitor Oliveira 0e0261b52e Fix obsoleted method URI.unescape in activesupport/test 2018-08-15 18:00:45 -03:00
Kasper Timm Hansen 977d77e9e2
Merge pull request #33499 from lsylvester/caller-ignore-paths
use BacktraceCleaner for ActiveRecord verbose logging
2018-08-15 20:16:43 +02:00
Ryuta Kamizono 111643b8a3
Merge pull request #33612 from bogdanvlviv/test-assert_called
Test `assert_called` and `assert_called_with`
2018-08-15 14:48:53 +09:00
bogdanvlviv b71abb3bb8
Refactor `Array#extract!`
Avoid allocating the second array by using `Array#reject!` instead of
`Enumerable#partition` in `Array#extract!`.

There are benchmarks in order to ensure that the changes speed up the method:
```
begin
  require "bundler/inline"
rescue LoadError => e
  $stderr.puts "Bundler version 1.10 or later is required. Please update
your Bundler"
  raise e
end

class Array
  def extract_v1!(&block)
    unless block_given?
      to_enum(:extract!) { size }
    else
      extracted_elements, other_elements = partition(&block)

      replace(other_elements)

      extracted_elements
    end
  end

  def extract_v2!
    return to_enum(:extract!) { size } unless block_given?

    extracted_elements = []

    reject! do |element|
      extracted_elements << element if yield(element)
    end

    extracted_elements
  end
end

gemfile(true) do
  source "https://rubygems.org"

  gem "benchmark-ips"
end

arrays_for_partition = Array.new(1000) { (0..10000).to_a }
arrays_for_extract_v1 = Array.new(1000) { (0..10000).to_a }
arrays_for_extract_v2 = Array.new(1000) { (0..10000).to_a }

Benchmark.ips do |x|
  x.report("Array#partition")  do
    arrays_for_partition.each do |numbers|
      odd_numbers, numbers = numbers.partition { |number| number.odd? }
      numbers
    end
  end

  x.report("Array#extract_v1!")  do
    arrays_for_extract_v1.each do |numbers|
      odd_numbers = numbers.extract_v1! { |number| number.odd? }
      numbers
    end
  end

  x.report("Array#extract_v2!")  do
    arrays_for_extract_v2.each do |numbers|
      odd_numbers = numbers.extract_v2! { |number| number.odd? }
      numbers
    end
  end

  x.compare!
end
```

The result of the benchmarks:

```
ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
```

```
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies...
Using benchmark-ips 2.7.2
Using bundler 1.16.1
Warming up --------------------------------------
     Array#partition     1.000  i/100ms
   Array#extract_v1!     1.000  i/100ms
   Array#extract_v2!     1.000  i/100ms
Calculating -------------------------------------
     Array#partition      1.390  (± 0.0%) i/s -      7.000  in   5.044843s
   Array#extract_v1!      2.781  (± 0.0%) i/s -     14.000  in   5.050589s
   Array#extract_v2!      3.151  (± 0.0%) i/s -     16.000  in   5.080608s

Comparison:
   Array#extract_v2!:        3.2 i/s
   Array#extract_v1!:        2.8 i/s - 1.13x  slower
     Array#partition:        1.4 i/s - 2.27x  slower
```

Avoid `unless`/`else` in favour of an early return.
The double-negative of that `else` can be confusing,
even though the code layout is nearly the same.
Also using of early return would improve `git diff`
if we needed to change this method.
2018-08-14 19:53:12 +03:00
bogdanvlviv 77b0126054
Add `Array#extract!`
The method removes and returns the elements for which the block returns a true value.
If no block is given, an Enumerator is returned instead.

```
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9]
numbers # => [0, 2, 4, 6, 8]
```
2018-08-14 19:53:12 +03:00
bogdanvlviv 88439585ed
Test `assert_called` and `assert_called_with`
- ActiveSupport::Testing::MethodCallAssertions#assert_called
  - Ensure that the method stubbed by `assert_called` returns correct value after
- ActiveSupport::Testing::MethodCallAssertions#assert_called_with
  - Ensure that `#assert_called_with` stubs the method to return a specific value
  - Ensure that the method stubbed by `assert_called_with` returns correct value after
2018-08-14 09:01:01 +03:00
Lachlan Sylvester c675783eb4 Use backtrace cleaner to clean up backtrace for verbose query logs 2018-08-14 09:15:28 +10:00
utilum a72bca8230 Add method_call_assertions and use them instead of Mocha
Six Mocha calls prove quite resistant to Minitestification. For example,
if we replace

```
  ActiveRecord::Associations::HasManyAssociation
    .any_instance
    .expects(:reader)
    .never
```

with `assert_not_called`, Minitest wisely raises

```
NameError: undefined method `reader' for class `ActiveRecord::Associations::HasManyAssociation'
```

as `:reader` comes from a deeply embedded abstract class,
`ActiveRecord::Associations::CollectionAssociation`.

This patch tackles this difficulty by adding
`ActiveSupport::Testing::MethodCallAsserts#assert_called_on_instance_of`
which injects a stubbed method into `klass`, and verifies the number of
times it is called, similar to `assert_called`. It also adds  a convenience
method, `assert_not_called_on_instance_of`, mirroring
`assert_not_called`.

It uses the new method_call_assertions to replace the remaining Mocha
calls in `ActiveRecord` tests.

[utilum + bogdanvlviv + kspath]
2018-08-13 13:05:14 +02:00
Robin Dupret 482b74e793 Fix a typo in Active Support's CHANGELOG [ci skip] 2018-08-10 06:24:25 +09:00
Kazuhiro Sera 52919f3d13 Fix the obvious typos detected by github.com/client9/misspell 2018-08-08 21:55:46 +09:00
bogdanvlviv 7867603fbb
Move changelog entry of 47018a82 up [ci skip]
We always add new entries on the top of changelog file.
This commit moves the entry added in 47018a82 up in order to
preserve the chronology.
Follows up 3e2629eb7f
2018-08-05 20:14:53 +03:00
Martin 47018a829c Support skip nil for cache fetch (#25437)
* test case for fetch cache miss with skip_nil

* abondon nil cache if skip_nil specified

* ensure not cache key for skip nil

* add document with skip_nil for Store#fetch

* add a new change log entry for #25437
2018-08-05 09:42:16 -05:00
Fabian Mersch b1589f6712
Fix example in thread_mattr_accessor documentation 2018-07-31 11:44:56 +02:00
Ryuta Kamizono 2a8917d304 Remove unused require
"active_support/core_ext/module/aliasing" is no longer used since
#19434.
2018-07-31 09:50:16 +09:00
Ryuta Kamizono e8dd2bf857
Merge pull request #33325 from Edouard-chin/ec-deprecate-class-method
A regression in `deprecate_methods` was introduced in a982a42:
2018-07-31 07:55:39 +09:00
Edouard CHIN 015477ae91 A regression in deprecate_methods was introduced in a982a42:
- Refactoring alias_chain to Module#prepend broke the possibility to deprecate class methods since the module
  generated was prepended to the target's instance.

  A suggestion to fix this was  to use `AS#redefine_method` which would solve the
  problem but with the cost of redefining directly the method.
  Decided to go with the same alias_chain implementation as before instead.

- Fixes #33253
2018-07-30 18:12:56 -04:00
Kasper Timm Hansen 6db5b6dc43
Merge pull request #33467 from bdewater/chomp-unconditionally
Chomp will work without checking for end of the string
2018-07-30 20:39:54 +02:00
Yasuo Honda d35b06e2f0 cpu_time and allocations are 0 when JRuby is used
According to #33449 and #33468, cpu_time and allocations are 0 when
JRuby is used.

```ruby
$ ruby -v
jruby 9.2.1.0-SNAPSHOT (2.5.0) 2018-07-27 13b2df5 Java HotSpot(TM) 64-Bit Server VM 25.181-b13 on 1.8.0_181-b13 [linux-x86_64]
$ bundle exec ruby -w -Itest test/log_subscriber_test.rb -n test_event_attributes
Run options: -n test_event_attributes --seed 6231

F

Failure:
SyncLogSubscriberTest#test_event_attributes [test/log_subscriber_test.rb:84]:
Expected 0 to be > 0.

rails test test/log_subscriber_test.rb:78

Finished in 0.018983s, 52.6791 runs/s, 105.3582 assertions/s.
1 runs, 2 assertions, 1 failures, 0 errors, 0 skips
```
2018-07-30 15:10:30 +00:00
Bart de Water 0ab64b162f Only use CLOCK_PROCESS_CPUTIME_ID if it's defined
It's not defined on JRuby and unlike monotonic time, concurrent-ruby doesn't have an cross-platform abstraction for this.
2018-07-29 14:58:03 -04:00
Bart de Water 4c9c18e93a Chomp will work without checking for end of the string 2018-07-29 14:42:35 -04:00
Ryuta Kamizono 14931e537f Remove unused `require "active_support/core_ext/regexp"`
Ruby 2.4 has native `Regexp#match?`.

https://ruby-doc.org/core-2.4.0/Regexp.html#method-i-match-3F

Related #32034.
2018-07-29 14:51:00 +09:00
Bart de Water ff9bdc2744 Work around Performance/EndWith false positive
Rubocop warns about "Use String#end_with? instead of a regex match anchored to the end of the string",
it doesn't seem aware of the $` special variable like Performance/RegexpMatch
2018-07-28 18:56:17 -04:00
Ryuta Kamizono b4d91bb41f
Merge pull request #33441 from bogdanvlviv/remove-rubocop-comments-from-codebase
Remove Rubocop's comments from Rails code base
2018-07-27 09:05:41 +09:00
Aaron Patterson 9954ce5153
I cannot spell 2018-07-26 14:56:25 -07:00
Aaron Patterson 3699ec9d1b
Add changelog entry 2018-07-26 14:54:47 -07:00
Aaron Patterson 280670465a
fix arity check to use "parameters" for backwards compat 2018-07-26 13:54:42 -07:00
bogdanvlviv 1933fbaecf
Fix Rubocop offense
```
Offenses:

activesupport/lib/active_support/subscriber.rb:91:17:
C: Layout/SpaceAroundOperators: Operator = should be surrounded by a single space.
      event     = event_stack.pop
```
2018-07-26 23:40:30 +03:00
Aaron Patterson 4cdedb571c
Always subscribe to event objects via `AS::Notifications.subscribe`
We don't need to have a special subscribe method for objects.  The
regular `subscribe` method is more expensive than a specialized method,
but `subscribe` should not be called frequently.  If that turns out to
be a hotspot, we can introduce a specialized method.  :)
2018-07-26 12:15:41 -07:00
Aaron Patterson 5e0c423881
Subscribe to event objects via `subscribe` 2018-07-26 12:05:23 -07:00
Aaron Patterson b0a16a9776
Subscribe to event objects via `subscribe_event`
Fanout notifier can send event objects to subscribers now.  Also moved
`end` lower in the `finish!` method to guarantee that CPU time is
shorter than real time.
2018-07-26 12:03:31 -07:00
Aaron Patterson 0c0dba1caf
Match the units in `duration` (milliseconds) 2018-07-26 11:49:22 -07:00
Eileen Uchitelle 42fec4b8de Add cpu_time, idle_time, and allocations to Event
* Use process clock instead of Time.now

This fixes any issues with the system clock changing and also eliminates
2 object allocations per event.

* Add start! and finish! methods to the event object so we can record
more information

* Adds cpu time, idle time, and allocation count for a particular event.

Co-authored-by: Aaron Patterson <aaron.patterson@gmail.com>
2018-07-26 13:57:51 -04:00
Richard Schneeman 91fd679710
Merge pull request #32381 from q-centrix/update-codeclimate-configs
Turn on performance based cops
2018-07-25 16:00:33 -05:00
Daniel Amireh 40cfbae94a
Update with_options.rb
explicit mapping for enum accepts a Hash not an Array, plus the example is using `.keys` which also exists on hash
2018-07-25 18:03:14 +02:00
Matthew Draper ec387c6dd9
Merge pull request #33229 from albertoalmagro/albertoalmagro/prefer-rails-command-over-bin-rails
Prefer rails command over bin/rails
2018-07-25 04:10:29 +09:30
Dillon Welch d108288c2f
Turn on performance based cops
Use attr_reader/attr_writer instead of methods

method is 12% slower

Use flat_map over map.flatten(1)

flatten is 66% slower

Use hash[]= instead of hash.merge! with single arguments

merge! is 166% slower

See https://github.com/rails/rails/pull/32337 for more conversation
2018-07-23 15:37:06 -07:00
Edouard CHIN 48b6bacbc5 e4e1b62 broke `to_param` handling:
- There was an issue inside controller tests where order params were not respected, the reason
  was because we were calling `Hash#to_query` which sorts the results lexicographically.
  1e4e1b62 fixed that issue by not using `to_query` but instead a utility function provided by rack.
- However with the fix came another issue where it's now no longer possible to do this

  ```
   post :foo, params: { user: User.first }

   # Prior to the patch the controller will receive { "user" => "1" }
   # Whereas now you get { "user": "#<User: ...>" }
  ```

  The fix in this PR is to modify `Hash#to_query` to sort only when it
  doesn't contain an array structure that looks something like "bar[]"

  Ref https://github.com/rails/rails/pull/33341#issuecomment-404039396
2018-07-12 13:04:27 -04:00
emaxi 6e1a536ad4 Add missing documentation options to number_to_currency [ci skip] 2018-07-11 20:59:51 -03:00
lxxxvi 4baad7bec6 added tests for assert_no_difference with multiple expressions 2018-07-08 15:15:16 +02:00
Alberto Almagro 9c3748a648 Fix typo 'in via'
Substitutes 'in via' for 'by running'
2018-07-06 22:46:53 +02:00
Alberto Almagro 40b209db53 Recommend use of rails over bin/rails
As discussed in #33203 rails command already looks for, and runs,
bin/rails if it is present.

We were mixing recommendations within guides and USAGE guidelines,
in some files we recommended using rails, in others bin/rails and
in some cases we even had both options mixed together.
2018-07-06 22:46:35 +02:00
Rafael Mendonça França f1f88e2556
A Class is a Module so we remove one conditional 2018-07-04 14:55:53 -04:00
Rafael França 153a32b9a0
Merge pull request #33289 from Edouard-chin/ec-lazy-load-hooks
Use class_eval or instance_eval when triggering lazy load hooks
2018-07-04 14:13:54 -04:00
Edouard CHIN 6cf7a0b0e9 Use class_eval or instance_eval when triggering lazy load hooks:
- When lazy load hooks were triggered we were using
  `Object.instance_eval` which evaluates the block in the context of
  the class being passed. Most of the time that class was a
  `Class`. If one wants to define a instance method on the class then
  it wasn't possible.

  ```ruby
    class A; end;
    A.instance_eval do
      def foo
        puts 'bar'
      end
    end
    A.new.foo #> NoMethodError: undefined method `foo`
    A.foo #> bar
  ```
- This PR checks what object is passed when triggering the hooks and
  either call `class_eval` or `instance_eval`. My rational and assumptions being
  that if an instance of a class is passed, then the blocks needs to
  evaluate in the context of that instance (i.e. defining a method
  should only define it on that instance).
  On the other hand, if a Class or Module is passed when triggering
  hooks, then defining a method should define it on the class itself
- #32776 Pushed me to introduce this change
2018-07-03 23:29:43 -04:00
Kasper Timm Hansen 969577d960
Refactor #33254.
Firstly, increment and decrement shouldn't care about the particulars of
key expiry. They should only know that they have to pass that responsibility
on to somewhere else.

Secondly, it moves the key normalization back inside the instrumentation like
it was originally. I think that matches the original design intention or at
the very least it lets users catch haywire key truncation.

Thirdly, it moves the changelog entry to the top of the file, where new entries
go. I couldn't understand what the entry was saying so I tried to rewrite it.
2018-07-01 12:46:15 +02:00
Jason Lee 5394be374d Fix Cache :redis_store increment/decrement ttl check and add more tests. 2018-06-30 12:52:29 +08:00
Jason Lee 9d5b02ec50 Add :expires_in option support for RedisCacheStore increment/decrement method. 2018-06-29 15:52:12 +08:00
Eugene Kenny 376b687cb7 Add tests for duration multiplication and division
When multiplying or dividing a duration by a scalar, it's tempting to
operate directly on the duration's value in seconds and recompute the
parts from the result. However this loses information, as there are
multiple combinations of parts that map to any given number of seconds
(e.g. `2.weeks` or `336.hours`). This is especially problematic when
dealing with durations on the scale of months or years, as converting an
exact number of seconds to one of those intervals and then using the
resulting duration to modify a date will give the wrong result.
2018-06-25 13:48:35 +01:00
Rafael Mendonça França a078cf0189
Merge pull request #33106 from marcandre/datecalc
Improve some DateAndTime calculations
2018-06-11 15:50:38 -04:00
Marc-Andre Lafortune e1f31e85ff Use fetch for better error handling 2018-06-09 13:47:03 -04:00
Marc-Andre Lafortune dd7f8ca3cd Use same weekday correspondance as Date#wday.
DeepCover revealed that most of these `wday != 0 ? wday - 1 : 6`
were not entirely covered, i.e. the case of `wday == 0` was not tested:
https://deep-cover.github.io/rails-cover/activesupport/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb.html#L351

There's actually no valid reason to consider Sunday a special case,
so this commit simply reajusts the values used for calculations.
2018-06-09 13:46:21 -04:00
Ryuta Kamizono f4f9147b1e
Merge pull request #33078 from bogdanvlviv/add-remove-require
Add/Remove `require`
2018-06-09 17:20:36 +09:00
Rafael França a38928397d
Merge pull request #33087 from bogdanvlviv/document-CompareWithRange
Add `ActiveSupport::CompareWithRange` to API docs
2018-06-08 19:25:20 -04:00
bogdanvlviv ad59b71b80
Remove extra `include ActiveSupport::Testing::MethodCallAssertions`
It includes via `require "abstract_unit"`.
2018-06-08 23:59:56 +03:00
bogdanvlviv b4ad3d815d
Add `ActiveSupport::CompareWithRange` to API docs
Since it is documented in the guides
http://edgeguides.rubyonrails.org/active_support_core_extensions.html#include-questionmark-and-cover-questionmark
we can add it to API docs http://edgeapi.rubyonrails.org too.

[ci skip]
2018-06-07 22:12:15 +03:00
bogdanvlviv ee6bbe403c
Add missing `require`
`activesupport/test/logger_test.rb` requires `tmpdir`.

`activesupport/test/multibyte_test_helpers.rb` requires
`filutils`, `open-uri`, and `tmpdir`.
2018-06-07 15:34:30 +03:00
bogdanvlviv 887c55c565
Remove unused `require`
- `activesupport/multibyte_normalization_conformance_test.rb`
  `fileutils`, `tmpdir`, and `open-uri` are unused since
  c245ca30f2,
  c245ca30f2, and
  7d7c2d13ba in accordance.

- `activesupport/test/multibyte_conformance_test.rb`
  `tmpdir`, and `open-uri` are unused since
  c245ca30f2, and
  7d7c2d13ba in accordance.
  Remove using of `fileutils` since
  c245ca30f2.

- `activesupport/test/multibyte_grapheme_break_conformance_test.rb`
  `fileutils`, `tmpdir`, and `open-uri` are unused since
  c245ca30f2,
  c245ca30f2, and
  7d7c2d13ba in accordance.
2018-06-07 15:34:31 +03:00
yuuji.yaginuma 69d91cd6a6 Don't expose `Enumerable#_original_sum_with_required_identity` which is internal API [ci skip]
`:nodoc:` is specified, but unfortunately, it is exposed in the API doc.
http://edgeapi.rubyonrails.org/classes/Enumerable.html#method-i-_original_sum_with_required_identity

If the method of the `alias` destination is public, the specification of
`:nodoc:` does not seem to work.
2018-06-04 09:53:59 +09:00
Michael Gee f21c6d7857 [ci skip] "brethen" is misspelled and unclear 2018-05-31 09:28:29 -04:00
Rafael França e6ef1fe056
Merge pull request #33020 from joshpencheon/time_zone_frac_microseconds
Align Time.zone.at method signature with that of Time::at
2018-05-30 15:32:37 -04:00
Josh Pencheon 45762cec03 Allow Time.zone.at to receive a second argument
For parity with Ruby's Time::at
2018-05-30 13:47:39 +01:00
yuuji.yaginuma ced104d579 Remove unused `require "active_support/file_update_checker"`
This is unnecessary since #22269.
2018-05-30 21:16:59 +09:00
Aaron Sumner a2a3fa8d7d Improve grammar for DateAndTime before? and after? calculations [ci skip] 2018-05-24 15:42:08 -07:00
Rafael França be43b1f6de
Merge pull request #32822 from lxxxvi/improved_error_message_in_assert_changes
Clearer error message in assert_changes
2018-05-22 18:17:11 -04:00
Rafael França 2b2bf2c73b
Merge pull request #32851 from yskkin/doc_require_dependency
Document require_dependency [ci skip]
2018-05-22 17:47:06 -04:00
utilum e04a79e772 add CHANGELOG/Doc 2018-05-22 15:56:36 +02:00
utilum 0fcb921a65 Allow Range#=== and Range#cover? on Range
ruby/ruby@989e07c features switching `Range#===` to use internal `r_cover_p`
instead of rubyland `include?`. This breaks expected behavior of
`ActiveSupport::CoreExt::Range` documented since at least 8b67a02.

This patch adds overrides on `Range#cover?` and `Range#===` and places all
three in a single module, `CompareWithRange`.

*Requiring core_ext/range/include_range now causes a deprecation warnning*
2018-05-22 14:38:19 +02:00
Kasper Timm Hansen 429f15ff7f
[ci skip] Add documentation/changelog entry. 2018-05-21 17:46:05 +02:00
Kasper Timm Hansen 39c22303a6
Add Enumerable#index_with.
In the app I'm working on I've wished that index_by had a buddy that would
assign the hash value instead of the key multiple times.

Enter index_with. Useful when building a hash from a static list of
symbols. Before you'd do:

```ruby
POST_ATTRIBUTES.map { |attr_name| [ attr_name, public_send(attr_name) ] }.to_h
```

But now that's a little clearer and faster with:

````ruby
POST_ATTRIBUTES.index_with { |attr_name| public_send(attr_name) }
```

It's also useful when you have an enumerable that should be converted to a hash,
but you don't want to muddle the code up with the overhead that it takes to create
that hash. So before, that's:

```ruby
WEEKDAYS.each_with_object(Hash.new) do |day, intervals|
  intervals[day] = [ Interval.all_day ]
end
```

And now it's just:

```ruby
WEEKDAYS.index_with([ Interval.all_day ])
```

It's also nice to quickly get a hash with either nil, [], or {} as the value.
2018-05-21 17:44:54 +02:00
Rafael Mendonça França a213ac360f
Raise a better exception when a invalid depreation behavior is set
Fixes #32928.
2018-05-18 13:35:09 -04:00
Ryuta Kamizono 1dc17e7b2e Fix `CustomCops/AssertNot` to allow it to have failure message
Follow up of #32605.
2018-05-13 11:32:47 +09:00
Yoshiyuki Kinjo c16352cc3c Document require_dependency [ci skip] 2018-05-09 13:20:02 +09:00
Ryuta Kamizono 1c70756e1a Remove `test_match_p` since Rails 6 requires Ruby 2.4.1 or newer
Follow up of #32034.
2018-05-07 04:19:24 +09:00
lxxxvi f4f7659acf Clearer error message in assert_changes
When `to:` is passed to `assert_changes`, it now prints the well-known `"Expected: x\n Actual: y"` message. 
Before, the message only contained the actual value.
2018-05-05 14:11:59 +02:00
Neil Souza bfddb67197 Fix #29632 - nil #path leads to NoMethodError in LoadError#is_missing?
See #29632 for details. In short, it's possible to enter `LoadError#is_missing?` when `LoadError#path` returns `nil`, leading to `path.sub` throwing an none-to-helpful `NoMethodError`.

This tiniest of patch inserts `#to_s` before the `sub` call to make sure it succeeds. Affected surface area should be just as tiny since something has already gone wrong to get us into `#is_missing?` and the current behavior when `#path` returns `nil` seems clearly not intended.

[Gannon McGibbon + Neil Souza]
2018-05-04 10:47:18 -04:00
Pavel Valena e04912393a Fix test: threads being nil in ensure
when connection_pool is not installed.
2018-04-30 17:32:37 +02:00
Ryuta Kamizono 0c54fc460e Improve the performance of `ActiveSupport::Inflector.ordinal`
This improves the performance for the most ordinalized numbers (1st,
2nd, 3rd, etc).

```
require "benchmark/ips"

def o1(number)
  abs_number = number.to_i.abs

  if (11..13).include?(abs_number % 100)
    "th"
  else
    case abs_number % 10
    when 1; "st"
    when 2; "nd"
    when 3; "rd"
    else    "th"
    end
  end
end

def o3(number)
  case number
  when 1; "st"
  when 2; "nd"
  when 3; "rd"
  when 4, 5, 6, 7, 8, 9, 10, 11, 12, 13; "th"
  else
    num_modulo = number.to_i.abs % 100
    if 11 <= num_modulo && num_modulo <= 13
      "th"
    else
      case num_modulo % 10
      when 1; "st"
      when 2; "nd"
      when 3; "rd"
      else    "th"
      end
    end
  end
end

def o4(number)
  case number
  when 1; "st"
  when 2; "nd"
  when 3; "rd"
  when 4, 5, 6, 7, 8, 9, 10, 11, 12, 13; "th"
  else
    num_modulo = number.to_i.abs % 100
    num_modulo %= 10 if num_modulo > 13
    case num_modulo
    when 1; "st"
    when 2; "nd"
    when 3; "rd"
    else    "th"
    end
  end
end

puts RUBY_DESCRIPTION
Benchmark.ips do |x|
  x.report("orig") { o1(1); o1(2); o1(3); o1(4); o1(11); o1(111); o1(1523) }
  x.report("ord3") { o3(1); o3(2); o3(3); o3(4); o3(11); o3(111); o3(1523) }
  x.report("ord4") { o4(1); o4(2); o4(3); o4(4); o4(11); o4(111); o4(1523) }
  x.compare!
end
```

```
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin15]
Warming up --------------------------------------
                orig    25.305k i/100ms
                ord3   121.146k i/100ms
                ord4   124.944k i/100ms
Calculating -------------------------------------
                orig    275.496k (± 2.4%) i/s -      1.392M in   5.054720s
                ord3      1.649M (± 5.0%) i/s -      8.238M in   5.009801s
                ord4      1.700M (± 7.0%) i/s -      8.496M in   5.031646s

Comparison:
                ord4:  1700059.6 i/s
                ord3:  1649154.9 i/s - same-ish: difference falls within error
                orig:   275496.3 i/s - 6.17x  slower
```

Closes #25020.

[lvl0nax, Jeremy Daer, Ryuta Kamizono]
2018-04-29 20:21:58 +09:00
Rafael França bb2a3afafb
Merge pull request #32733 from Edouard-chin/ec-setupand-teardown
`SetupAndTeardown` has few caveats that breaks libraries
2018-04-27 16:20:16 -04:00
Edouard CHIN 1cf8b6c231 `SetupAndTeardown` has few caveats that breaks libraries:
- In #32472 I introduced a fix in order for all `after_teardown` method provided by libraries and Rails to run, even if the application's `teardown` method raised an error (That's the default minitest behavior). However this change wasn't enough and doesn't take in consideration the ancestors chain.
  If a library's module containing an `after_teardown` method get included after the `SetupAndTeardown` module (one example is the [ActiveRecord::TestFixtures module](7d2400ab61/activerecord/lib/active_record/fixtures.rb (L855-L856)), then the ancestors of the test class would look something like
  ```ruby
    class MyTest < ActiveSupport::TestCase
    end

    puts MyTest.ancestors # [MyTest, ActiveSupport::TestCase, ActiveRecord::TestFixtures, ActiveSupport::Testing::SetupAndTeardown]
  ```
  Any class/module in the ancestors chain that are **before** the `ActiveSupport::Testing::SetupAndTeardown` will behave incorrectly:
    - Their `before_setup` method will get called **after** all regular setup method
    - Their `after_teardown` method won't even get called in case an exception is raised inside a regular's test `teardown`

  A simple reproduction script of the problem here https://gist.github.com/Edouard-chin/70705542a59a8593f619b02e1c0a188c

- One solution to this problem is to have the `AS::SetupAndTeardown` module be the very first in the ancestors chain. By doing that we ensure that no `before_setup` / `after_teardown` get executed prior to running the teardown callbacks
2018-04-27 01:36:27 -04:00
Akira Matsuda 124c082d43 Don't dup Strings when jsonifying
This method would be called so many times and would create so many temporary garbage Strings
2018-04-27 03:57:08 +09:00
Akira Matsuda ac93e7b5c1 Reduce extra object creations in TaggedLogging
tags_text method creates 3 Ruby objects per each logger call when no custom tags are given
(which is the default setting, and so presumably the majority use case).
This patch reduces two temporary object creations in this case.

    require 'allocation_tracer'
    ObjectSpace::AllocationTracer.setup(%i{type})

    tags = ['a']

    pp before: ObjectSpace::AllocationTracer.trace {
      tags.collect { |tag| "[#{tag}] " }.join
    }

    pp after: ObjectSpace::AllocationTracer.trace {
      "[#{tags[0]}] "
    }

    {:before=>{[:T_ARRAY]=>[1, 0, 0, 0, 0, 0], [:T_STRING]=>[2, 0, 0, 0, 0, 0]}}
    {:after=>{[:T_STRING]=>[1, 0, 0, 0, 0, 0]}}
2018-04-27 01:59:32 +09:00
Ryuta Kamizono 222f20eb19
Merge pull request #32681 from bdewater/rubocop-0-54
Rubocop 0.54
2018-04-22 13:27:36 +09:00
yuuji.yaginuma 58e18c1aaf Fix typo in constant name [ci skip] 2018-04-22 08:35:36 +09:00
Bart de Water 999e7ec505 Fix Style/RedundantReturn offenses 2018-04-21 13:23:42 -04:00
Andrew White ddca53e067
Merge pull request #32642 from bogdanvlviv/fix-name-test-added-by-32613
Fix name of the test added by #32613
2018-04-20 05:14:49 -04:00
bogdanvlviv f8cbc1dd6e
Return back "/" to the end of RAILS_GEM_ROOT
- The "/" was removed in 40bdbce191 during
refactoring. It may cause regression since looks like was added
intentionaly because it is possible that a name of any another gem
can start with /rails/, so slash was added to ensure that it is "rails"
gem.
I would like to backport this to `5-2-stable` too.

- Use `__dir__` instead of `__FILE__`. Follow up #29176.
2018-04-20 01:24:46 +03:00
Rafael França d26f48a574
Merge pull request #32648 from bogdanvlviv/improve-pattern-filenames-to-catch-more-style-offences
Allow rubocop check more files
2018-04-19 17:04:01 -04:00
bogdanvlviv 1a42d87e3b
Allow rubocop check more files
This commit fix pattern of filenames for `CustomCops/AssertNot` and
`CustomCops/RefuteNot`.

rubocop should check every file under `test/`.

Related to #32441, #32605
2018-04-19 23:25:39 +03:00
Rafael França cddcc1dac4
Merge pull request #32168 from christianblais/activesupport-ordinalize-i18n
`#ordinal` and `#ordinalize` now support I18n
2018-04-19 16:19:02 -04:00
Rafael França 6fec9c27e5
Merge pull request #32605 from composerinteralia/assert-not
Add RuboCop for `assert_not` over `assert !`
2018-04-19 15:03:28 -04:00
bogdanvlviv e6970c42d5
Fix name of the test added by #32613 2018-04-19 21:19:51 +03:00
Daniel Colson a1ac18671a Replace `assert !` with `assert_not`
This autocorrects the violations after adding a custom cop in
3305c78dcd.
2018-04-19 08:11:33 -04:00