Commit Graph

2059 Commits

Author SHA1 Message Date
Dylan Thacker-Smith
99c87ad247 Improve model attribute accessor method names for backtraces
Ruby uses the original method name, so will show the __temp__ method
name in the backtrace. However, in the common case the method name
is compatible with the `def` keyword, so we can avoid the __temp__
method name in that case to improve the name shown in backtraces
or TracePoint#method_id.
2018-10-12 09:50:10 -07:00
Gannon McGibbon
c401c43850 Fix call sites 2018-10-02 15:31:29 -04:00
Sharang Dashputre
3c4b729f48 Fix spellings for 'unmarshall(ing/ed)' & 'marshall(ing/ed)' 2018-10-02 13:55:39 +05:30
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
Rafael França
6556898884
Merge pull request #30676 from artofhuman/import-assert-attrs-error-message
Improve error message when assign wrong attributes to model
2018-09-26 14:10:24 -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
Ryuta Kamizono
c3e569550c
Merge pull request #33804 from yskkin/num_string
Fix non_numeric_string?
2018-09-08 05:56:22 +09:00
Rafael França
dd29fabebf
Merge pull request #33615 from Larochelle/i18n_full_message_with_nested_attributes
`ActiveModel.full_message` interaction with `index_errors`
2018-09-07 13:24:09 -04:00
Yoshiyuki Kinjo
ba406d9c22 Fix non_numeric_string?
For example, dirty checking was not right for the following case:

```
model.int_column = "+5"
model.float_column = "0.5E+1"
model.decimal_column = "0.5e-3"
```

It is enough to see whether leading character is a digit for avoiding
invalid numeric expression like 'wibble' to be type-casted to 0, as
this method's comment says.

Fixes #33801
2018-09-07 16:17:15 +09:00
Ryuta Kamizono
736edb9828 Formatting CHANGELOGs [ci skip]
Fixing code block rendering, indentation, backticks, etc.
2018-09-07 07:59:19 +09:00
schneems
e81b0ddd7a Faster time_value.rb
The multiplication of the value takes a long time when we can instead mutate and use the string value directly.

The `microsec` perf increases speed by 27% in the ideal case (which is the most common).

```
original_string = ".443959"

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report("multiply") { 
    string = original_string.dup
    (string.to_r * 1_000_000).to_i 
  }
  x.report("new     ") { 
    string = original_string.dup
    if string && string.start_with?(".".freeze) && string.length == 7
      string[0] = ''.freeze
      string.to_i
    end
  }
  x.compare!
end

# Warming up --------------------------------------
#             multiply   125.783k i/100ms
#             new        146.543k i/100ms
# Calculating -------------------------------------
#             multiply      1.751M (± 3.3%) i/s -      8.805M in   5.033779s
#             new           2.225M (± 2.1%) i/s -     11.137M in   5.007110s

# Comparison:
#             new     :  2225289.7 i/s
#             multiply:  1751254.2 i/s - 1.27x  slower
```
2018-08-29 11:45:47 -05:00
Ryuta Kamizono
47a6d788dd Fix numericality validator to still use value before type cast except Active Record
The purpose of fe9547b is to work type casting to value from database.

But that was caused not to use the value before type cast even except
Active Record.

There we never guarantees that the value before type cast was going to
the used in this validation, but we should not change the behavior
unless there is some particular reason.

To restore original behavior, still use the value before type cast if
`came_from_user?` is undefined (i.e. except Active Record).

Fixes #33651.
Fixes #33686.
2018-08-24 00:44:02 +09:00
Martin Larochelle
8d2f3179e6 Call human_attribute_name with a string instead of a symbole 2018-08-16 11:50:13 -04:00
Martin Larochelle
0b54641878 ActiveModel.full_message interaction with index_errors 2018-08-14 12:01:23 -04:00
Ryuta Kamizono
2fece9036d Fix numericality validator not to be affected by custom getter
Since fe9547b6, numericality validator would parse raw value only when a
value came from user to work type casting to a value from database.

But that was caused a regression that the validator would work against
getter value instead of parsed raw value, a getter is sometimes
customized by people. #33550

There we never guarantees that the value before type cast was going to
the used in this validation (actually here is only place that getter
value might not be used), but we should not change the behavior unless
there is some particular reason.

The purpose of fe9547b6 is to work type casting to a value from
database. We could achieve the purpose by using `read_attribute`,
without using getter value.

Fixes #33550.
2018-08-13 23:28:46 +09:00
bogdanvlviv
159dc60bee
Add changelog entry for #31503 [ci skip]
Related to #31503
2018-08-12 15:38:47 +03:00
bogdanvlviv
3a0a8cf604
Fix test failure
```
...
(snip)
............F
Failure:
JsonSerializationTest#test_as_json_should_return_a_hash_if_include_root_
in_json_is_true [/home/travis/build/rails/rails/activemodel/test/cases/serializers/json_serialization_test.rb:145]:
Expected: 2006-08-01 00:00:00 UTC
  Actual: "2006-08-01T00:00:00.000Z"
rails test home/travis/build/rails/rails/activemodel/test/cases/serializers/json_serialization_test.rb:136
(snip)
...
```

Related to #31503
2018-08-11 19:19:04 +03:00
Eileen M. Uchitelle
09e1452eeb
Merge pull request #31503 from bogdan/timestamp-as-json
Fix AM::Serializers::JSON#as_json method for timestamps
2018-08-11 10:37:49 -04:00
Bart
eb4f7cad20 ActiveModel::Naming delegate match? in the same manner as =~ and != (#33466)
The purpose of the module seems to quack like a string.
2018-07-29 19:58:35 +02:00
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
Ryuta Kamizono
a4398e412c Merge pull request #30919 from seanlinsley/17622-before_save_strict_arguments
Add strict argument checking to ActiveRecord callbacks
2018-07-23 04:19:37 +09:00
Sean Linsley
dfb0e4b3dc add strict argument checking to ActiveRecord callbacks
This ends up adding it to all save-related callbacks defined in `ActiveRecord::DefineCallbacks`, including e.g. `after_create`. Which should be fine: they didn't support `:on` in the first place.
2018-07-22 12:51:47 -05:00
Jeremy Baker
a19918124d Ensure attribute is a symbol in the added? method 2018-07-14 13:19:46 -05:00
bogdanvlviv
e62e68e25b
has_secure_password: use recovery_password instead of activation_token
Since we have `has_secure_token`, it is too confusing to use `_token`
suffix with `has_secure_password`.
Context https://github.com/rails/rails/pull/33307#discussion_r200807185
2018-07-08 14:12:27 +03:00
bogdanvlviv
382b5ca7dd
Improve SecurePasswordTest#test_authenticate
- Ensure that execution of `authenticate`/`authenticate_XXX` returns
`self` if password is correct, otherwise `false` (as mentioned in the documentation).
- Test `authenticate_password`.
2018-07-06 20:21:58 +03:00
claudiob
0cd36e2b22 Shorter code: remove unnecessary condition
See 136fc65c9b (r28897107)

 I _think_ that this method can now be rewritten from:

```ruby
def attribute_previous_change(attr)
  previous_changes[attr] if attribute_previously_changed?(attr)
end
```

to:

```ruby
def attribute_previous_change(attr)
  previous_changes[attr]
end
```

without losing performance.

---

Calling

```ruby
previous_changes[attr] if attribute_previously_changed?(attr)
```

is equivalent to calling

```ruby
previous_changes[attr] if previous_changes.include?(attr)
```

When this commit 136fc65c9b was made, Active Record had its own `previous_changes` method, added here below. However, that method has been recently removed from the codebase, so `previous_changes` is now only the method defined in Active Model as:

```ruby
def previous_changes
  @previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new
  @previously_changed.merge(mutations_before_last_save.changes)
end
```

Since we are dealing with a memoized Hash, there is probably no need to check `if .include?(attr_name)` before trying to fetch `[attr]` for it.

Does that make sense? Did I miss anything? Thanks!
2018-07-05 06:08:31 -07:00
utilum
e862ee86b7 Fix Ruby warnings tickled by the test suite 2018-06-30 10:20:45 +02:00
Rafael Mendonça França
08dde0f355
Merge pull request #26764 from choncou/improve_has_secure_password
Allow configurable attribute name on `#has_secure_password`
2018-06-28 13:01:21 +02:00
bogdanvlviv
f009e553ce
Add changelog for #32956 [ci skip]
Add mention about default value of `config.active_model.i18n_full_message`.
2018-06-12 01:39:32 +03:00
bogdanvlviv
d1941fe6da
Fix active_model/errors docs [ci skip]
- Fix indentation.
- Add a missing dot to the end of the sentence.

Related to #32956
2018-06-12 00:32:25 +03:00
Rafael França
d3f659e526
Merge pull request #32956 from Shopify/i18n_activemodel_errors_full_message
Allow to override the full_message error format
2018-06-11 10:10:23 -04:00
Sam
a46dcb7454 PERF: avoid allocating column names where possible
When requesting columns names from database adapters AR:Result
would dup/freeze column names, this prefers using fstrings which
cuts down on repeat allocations

Attributes that are retained keep these fstrings around for the long
term

Note, this has the highest impact on "short" result sets, eg: Topic.first where you can void allocating the number of columns * String.
2018-06-06 09:50:58 +10:00
Martin Larochelle
32513c4b35 Add global config for config.active_model.i18n_full_message 2018-06-05 13:25:24 -04:00
Ryuta Kamizono
34cc301f03 Ensure casting by boolean attribute when querying
`QueryAttribute#value_for_database` calls only `type.serialize`, and
`Boolean#serialize` is a no-op unlike other attribute types.

It caused the issue #32624. Whether or not `serialize` will invoke
`cast` is undefined in our test cases, but it actually does not work
properly unless it does so for now.

Fixes #32624.
2018-05-29 05:22:31 +09:00
Ryuta Kamizono
fe9547b6fb Parse raw value only when a value came from user in numericality validator
Since `parse_raw_value_as_a_number` may not always parse raw value from
database as a number without type casting (e.g. "$150.55" as money
format).

Fixes #32531.
2018-05-28 10:12:15 +09:00
Ryuta Kamizono
8a60018355 Make force equality checking more strictly not to allow serialized attribute
Since #26074, introduced force equality checking to build a predicate
consistently for both `find` and `create` (fixes #27313).

But the assumption that only array/range attribute have subtype was
wrong. We need to make force equality checking more strictly not to
allow serialized attribute.

Fixes #32761.
2018-05-25 23:55:38 +09:00
Martin Larochelle
7d09874a71 Allow to override the full_message error format 2018-05-22 16:31:30 -04:00
Annie-Claude Côté
6ff593ef87 Fix user_input_in_time_zone to coerce non valid string into nil
Before it was coercing an invalid string into "2000-01-01 00:00:00".
2018-05-16 17:01:07 -04:00
Annie-Claude Côté
35bf8e90b1 Add missing require for string to timezone conversion
Inside user_input_in_time_zone we call in_time_zone on the value and value can be a String.
2018-05-16 15:48:12 -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
Semyon Pupkov
2253f6cca1 Improve error message when assign wrong attributes to model 2018-04-28 16:27:16 +05: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
Cassidy Kobewka
8b13506217
Update validates_inclusion_of example 2018-04-17 21:16:33 -04:00
Cassidy Kobewka
3137a8739e
Use string-based fields. [ci skip] 2018-04-16 19:09:45 -04:00
Cassidy Kobewka
2aa8e0a56f
Inclusive Language in Documentation Examples [ci skip] 2018-04-15 12:34:30 -04:00
Ryuta Kamizono
eb3740dcb0
Merge pull request #32498 from eugeneius/mutation_tracker_merge_changes
Prevent changes_to_save from mutating attributes
2018-04-10 13:18:34 +09:00
Eugene Kenny
80a09caedc Prevent changes_to_save from mutating attributes
When an array of hashes is added to a `HashWithIndifferentAccess`, the
hashes are replaced with HWIAs by mutating the array in place.

If an attribute's value is an array of hashes, `changes_to_save` will
convert it to an array of HWIAs as a side-effect of adding it to the
changes hash.

Using `merge!` instead of `[]=` fixes the problem, as `merge!` copies
any array values in the provided hash instead of mutating them.
2018-04-08 23:06:48 +01:00