Commit Graph

1581 Commits

Author SHA1 Message Date
Rafael França
77d3550f60 Merge pull request #25296 from kamipo/use_inspect_for_type_cast_for_schema
Use `inspect` in `type_cast_for_schema` for date/time and decimal values
2017-02-28 18:19:33 -05:00
Rafael Mendonça França
0683552b15
Match the behavior of bigdecimal after https://github.com/ruby/bigdecimal/pull/55 2017-02-24 19:43:09 -05:00
John Hawthorn
68926798a5
Fix invalid string Decimal casting under ruby 2.4
In Ruby 2.4, BigDecimal(), as used by the Decimal cast, was changed so
that it will raise ArgumentError when passed an invalid string, in order
to be more consistent with Integer(), Float(), etc. The other numeric
types use ex. to_i and to_f.

Unfortunately, we can't simply change BigDecimal() to to_d. String#to_d
raises errors like BigDecimal(), unlike all the other to_* methods (this
should probably be filed as a ruby bug).

Instead, this simulates the existing behaviour and the behaviour of the
other to_* methods by finding a numeric string at the start of the
passed in value, and parsing that using BigDecimal().

See also
https://bugs.ruby-lang.org/issues/10286
3081a627ce
2017-02-24 19:41:23 -05:00
Rafael Mendonça França
f4acdd83ff
Preparing for 5.1.0.beta1 release 2017-02-23 14:53:21 -05:00
Prem Sichanugrist
0b157f8ded Fix define_attribute_method with Symbol in AR
This issue is only appear when you try to call `define_attribute_method`
and passing a symbol in Active Record. It does not appear in isolation
in Active Model itself.

Before this patch, when you run `User.define_attribute_method :foo`, you
will get:

    NoMethodError: undefined method `unpack' for :foo:Symbol
        from activerecord/lib/active_record/attribute_methods/read.rb:28:in `define_method_attribute'
        from activerecord/lib/active_record/attribute_methods/primary_key.rb:61:in `define_method_attribute'
        from activemodel/lib/active_model/attribute_methods.rb:292:in `block in define_attribute_method'
        from activemodel/lib/active_model/attribute_methods.rb:285:in `each'
        from activemodel/lib/active_model/attribute_methods.rb:285:in `define_attribute_method'

This patch contains both a fix in Active Model and a test in Active
Record for this error.
2017-02-21 20:33:32 +09:00
namusyaka
b0be7792ad
Avoid converting integer as a string into float 2017-02-18 19:04:48 +09:00
Ryuta Kamizono
33860b3556 Remove :doc: for NumericalityValidator [ci skip]
The `:doc:` was added in cdb9d7f but `NumericalityValidator` is already
`:nodoc:` class. `:doc:` is unneeded.

https://github.com/rails/rails/blob/master/activemodel/lib/active_model/validations/numericality.rb#L3
2017-02-17 23:11:01 +09:00
Sen Zhang
d57356bd5a change ActiveModel::Validation to ActiveModel::Validations in comments 2017-02-15 14:29:04 -08:00
Corey Farwell
34867115b0 Indicate units of 'limit' in 'Integer' error message. 2017-02-15 10:38:31 -05:00
Ryuta Kamizono
416d85b65e
Remove unused require
These files are not using `strip_heredoc`.

Closes #27976
2017-02-12 19:38:49 -07:00
Rafael Mendonça França
3a25cdca3e
Remove deprecated behavior that halts callbacks when the return is false 2017-02-07 12:19:37 -03:00
yuuji.yaginuma
4f8d86c822 Remove ActiveModel::TestCase from lib
`ActiveModel::TestCase` is used only for the test of Active Model.
Also, it is a private API and can not be used in applications.
Therefore, it is not necessary to include it in lib.
2017-02-07 07:46:52 +09:00
Kir Shatrov
7ec30400e1 Make BigDecimal casting consistent on different platforms
Right now it behaves differently on JRuby:

```
--- expected
+++ actual
@@ -1 +1 @@
-#<BigDecimal:5f3c866c,'0.333333333333333333',18(20)>
+#<BigDecimal:16e0afab,'0.3333333333333333',16(20)>
```

My initial PR (https://github.com/rails/rails/pull/27324)
offered to let the precision to be decided by the platform and
change the test expection, but other contributors suggested
that we should change the default precision in Rails
to be consistent of all platforms.

The value (18) comes from the max default precision that comes
from casting Rational(1/3) to BigDecimal.
2017-01-22 10:28:01 -05:00
Scott González
e0fee7a71f Fix typo 2017-01-10 18:22:52 -05:00
Akira Matsuda
5473e390d3 self. is not needed when calling its own instance method
Actually, private methods cannot be called with `self.`, so it's not just redundant, it's a bad habit in Ruby
2017-01-05 19:58:52 +09:00
Kasper Timm Hansen
e42cbb7d31 Revert "Merge pull request #27528 from kamipo/extract_casted_booleans"
As pointed out by @matthewd this change makes ImmutableString aware
of MysqlString's existence whereas previously MysqlString was only
overriding public API.

cc @kamipo

This reverts commit e632c2fa4cb60072a778ce95c952a0fa95e5b074, reversing
changes made to 334a7dcf107cd3ff1697163d331d289d6d65dcd7.
2017-01-01 14:34:04 +01:00
Ryuta Kamizono
d8e5751a1d Extract casted_true/casted_false for Type::ImmutableString
The only difference between `Type::ImmutableString` and its subclasses
is the representation of the casted booleans. Prefer extracting
`casted_true`/`casted_false` and override these by subclasses.
2017-01-01 04:01:17 +09:00
Kasper Timm Hansen
621d063f6b [ci skip] Update Active Model copyright years.
Missed in 37d956f. Fixes #27524.

[ MSathieu & Kasper Timm Hansen ]
2016-12-31 17:38:13 +01:00
Akira Matsuda
cdb9d7f481 Privatize unneededly protected methods in Active Model 2016-12-24 12:18:16 +09:00
Akira Matsuda
53f537d1f8 No need to :nodoc: private methods 2016-12-24 12:11:06 +09:00
Akira Matsuda
21e5fd4a2a Describe what we are protecting 2016-12-23 23:48:54 +09:00
MSP-Greg
e41c6ec888 Change ActiveModel::Type::Helpers to :nodoc: [ci skip] 2016-12-16 13:35:37 -06:00
Ryuta Kamizono
b01740f908 Use inspect in type_cast_for_schema for date/time and decimal values
Currently dumping defaults on schema is inconsistent.

Before:

```ruby
  create_table "defaults", force: :cascade do |t|
    t.string   "string_with_default",   default: "Hello!"
    t.date     "date_with_default",     default: '2014-06-05'
    t.datetime "datetime_with_default", default: '2014-06-05 07:17:04'
    t.time     "time_with_default",     default: '2000-01-01 07:17:04'
    t.decimal  "decimal_with_default",  default: 1234567890
  end
```

After:

```ruby
  create_table "defaults", force: :cascade do |t|
    t.string   "string_with_default",   default: "Hello!"
    t.date     "date_with_default",     default: "2014-06-05"
    t.datetime "datetime_with_default", default: "2014-06-05 07:17:04"
    t.time     "time_with_default",     default: "2000-01-01 07:17:04"
    t.decimal  "decimal_with_default",  default: "1234567890"
  end
```
2016-12-11 22:57:29 +09:00
Rafael Mendonça França
0951306ca5
Make ActiveModel::Errors backward compatible with 4.2
If a Error object was serialized in the database as YAML in the Rails
4.2 version, if we load in the Rails 5.0 version it will miss the
@details instance variable so methods like #clear and #add will start to
fail.
2016-12-08 16:27:47 -05:00
Sean Griffin
ef76f83f4c Merge pull request #26696 from iainbeeston/only-ruby-types-in-activemodel
Moved database-specific ActiveModel types into ActiveRecord
2016-12-08 13:45:47 -05:00
Sean Griffin
55ebf6c1ac Merge pull request #27185 from kamipo/fix_apply_seconds_precision
Fix `apply_seconds_precision` not to be affected by `mathn`
2016-12-08 13:04:39 -05:00
Gabi Stefanini
b970ade252 Add Action View to Active Model API documentation
In Rails 4.1, Action View was extracted from Action Pack, but this
change was not reflected in the API documentation of ActiveModel::Model.
This commits makes it explicit in the documentation that Active Model
also interacts with Action View as well as Action Pack.

[ci skip]
2016-12-06 22:37:25 -05:00
Gabi Stefanini
f3d0762d6c Fixes API wording to match API conventions
In ActiveModel::Model API documentation, referrences to Rails
components were tagged with fixed-width font and named as if
they were modules.This fixes the inconsistency to match API
documentation conventions.

[ci skip]
2016-12-06 22:36:49 -05:00
Ryuta Kamizono
6700f85726 Fix apply_seconds_precision not to be affected by mathn
Currently `apply_seconds_precision` cannnot round usec
when after `require 'mathn'`.

```
irb(main):001:0> 1234 / 1000 * 1000
=> 1000
irb(main):002:0> 1234 - 1234 % 1000
=> 1000
irb(main):003:0> require 'mathn'
=> true
irb(main):004:0> 1234 / 1000 * 1000
=> 1234
irb(main):005:0> 1234 - 1234 % 1000
=> 1000
```
2016-11-27 08:22:38 +09:00
Kenichi Kamiya
9f566aba32 Allow indifferent access in ActiveModel::Errors
`#[]` has already applied indifferent access, but some methods does not.

  `#include?`, `#has_key?`, `#key?`, `#delete` and `#full_messages_for`.
2016-11-22 04:10:41 +09:00
Andrew White
0ef5b6c163 Merge pull request #26905 from bogdanvlviv/docs
Add missing `+` around a some literals.
2016-11-13 14:09:30 +00:00
Rafael Mendonça França
fe1f4b2ad5
Add more rubocop rules about whitespaces 2016-10-29 01:17:49 -02:00
Xavier Noria
7506f33906 removes requires already present in active_support/rails 2016-10-27 09:45:20 +02:00
Xavier Noria
56832e791f let Regexp#match? be globally available
Regexp#match? should be considered to be part of the Ruby core library. We are
emulating it for < 2.4, but not having to require the extension is part of the
illusion of the emulation.
2016-10-27 09:13:55 +02:00
bogdanvlviv
5faa9a235c Add missing + around a some literals.
Mainly around `nil`

[ci skip]
2016-10-27 00:27:47 +03:00
Akira Matsuda
be623bf55f Missing require extract_options 2016-10-25 09:35:21 +09:00
Vijay Dev
5741e87eea Merge branch 'master' of github.com:rails/docrails 2016-10-20 17:28:48 +00:00
Iain Beeston
994ce87bbd Moved database-specific ActiveModel types into ActiveRecord
ie. DecimalWithoutScale, Text and UnsignedInteger
2016-10-14 20:21:20 +01:00
Unathi Chonco
9b63bf1dfd Remove method for regenerating a token, and update #authenticate.
This change now creates a method `#authenticate_XXX` where XXX is
the configured attribute name on `#has_secure_password`. `#authenticate`
is now an alias to this method when the attribute name is the default
'password'
2016-10-12 09:01:57 +08:00
Unathi Chonco
86a48b4da3 This addition will now allow configuring an attribute name for the
existing `#has_secure_password`. This can be useful when one would
like to store some secure field as a digest, just like a password.

The method still defaults to `password`. It now also allows using the
same `#authenticate` method which now accepts a second argument for
specifying the attribute to be authenticated, or will default to 'password`.

A new method is also added for generating a new token for an attribute by
calling `#regenerate_XXXX` where `XXXX` is the attribute name.
2016-10-12 01:02:27 +08:00
Rafael Mendonça França
6a78e0ecd6
Removed deprecated :tokenizer in the length validator 2016-10-10 20:29:24 -03:00
Rafael Mendonça França
9de6457ab0
Removed deprecated methods in ActiveModel::Errors
`#get`, `#set`, `[]=`, `add_on_empty` and `add_on_blank`.
2016-10-10 20:22:15 -03:00
Sean Griffin
de9a56b66a Merge pull request #24571 from raimo/patch-1
Print the proper ::Float::INFINITY value when used as a default value
2016-10-04 17:37:04 -04:00
Iain Beeston
1e6aab94d5 Corrected comments referring to ActiveModel::Attributes
Should be ActiveRecord::Attributes (ActiveModel::Attributes does not exist)
2016-10-03 08:56:01 +01:00
Jean Boussier
33fd23e077 Do not leak the Errors default proc when calling to_hash or as_json 2016-09-27 14:33:16 +02:00
Andrey Molchanov
2003381bbb [ci skip] Fix bad examples in rdoc 2016-09-17 14:21:38 +03:00
Louis-Michel Couture
57e90ef5b1 Update ActiveModel::Dirty Doc [ci skip] 2016-09-16 10:57:04 -04:00
Louis-Michel Couture
da0532d9d1 Update ActiveModel::Dirty Doc [ci skip]
Fix potentially misleading example.
2016-09-15 17:34:42 -04:00
Ryuta Kamizono
3464cd5c28 Fix broken comments indentation caused by rubocop auto-correct [ci skip]
All indentation was normalized by rubocop auto-correct at 80e66cc4d90bf8c15d1a5f6e3152e90147f00772.
But comments was still kept absolute position. This commit aligns
comments with method definitions for consistency.
2016-09-14 18:26:32 +09:00
Alex Kitchens
fbccae4d19 Fix Remaining Case-In-Assignment Statement Formatting
Recently, the Rails team made an effort to keep the source code consistent, using Ruboco
(bb1ecdcc677bf6e68e0252505509c089619b5b90 and below). Some of the case
statements were missed.

This changes the case statements' formatting and is consistent with changes
in 810dff7c9fa9b2a38eb1560ce0378d760529ee6b and db63406cb007ab3756d2a96d2e0b5d4e777f8231.
2016-09-06 09:34:09 -05:00
Xavier Noria
db63406cb0 apply case-in-assignment pattern 2016-09-02 01:34:43 +02:00
Xavier Noria
810dff7c9f RuboCop is 100% green 🎉 2016-09-02 00:43:33 +02:00
Guillermo Iguaran
cec60d3989 validate_each in NumericalityValidator is never called in this case.
NumericalityValidator#validate_each is never called when allow_nil is true and
the value is nil because it is already skipped in EachValidator#validate.
2016-08-28 00:37:10 -05:00
Georg Ledermann
11f5434a8c Fix typo in deprecation message
This fixes a copy-and-paste-issue slipped in by #18996
2016-08-27 08:42:45 +02:00
Ryuta Kamizono
f006de5dc5 Fix broken alignments caused by auto-correct commit 411ccbd
Hash syntax auto-correcting breaks alignments. 411ccbdab2608c62aabdb320d52cb02d446bb39c
2016-08-10 06:36:39 +09:00
Xavier Noria
a9dc45459a code gardening: removes redundant selfs
A few have been left for aesthetic reasons, but have made a pass
and removed most of them.

Note that if the method `foo` returns an array, `foo << 1`
is a regular push, nothing to do with assignments, so
no self required.
2016-08-08 01:12:38 +02:00
Xavier Noria
b45c9ca9b6 revises most Lint/EndAlignment offenses
Some case expressions remain, need to think about those ones.
2016-08-07 23:41:00 +02:00
Xavier Noria
b326e82dc0 applies remaining conventions across the project 2016-08-06 20:20:22 +02:00
Xavier Noria
80e66cc4d9 normalizes indentation and whitespace across the project 2016-08-06 20:16:27 +02:00
Xavier Noria
411ccbdab2 remove redundant curlies from hash arguments 2016-08-06 19:44:11 +02:00
Xavier Noria
18a2513729 applies new string literal convention in activemodel/lib
The current code base is not uniform. After some discussion,
we have chosen to go with double quotes by default.
2016-08-06 18:38:02 +02:00
Xavier Noria
5a83f05424 systematic revision of =~ usage in AMo 2016-07-24 21:23:23 +02:00
David Elliott
3691c751e9 [ci skip] add class level documentation to ActiveModel::Type::Boolean
add documentation of the behaviors of type coercion at the class level
2016-07-11 07:29:58 -07:00
Rafael França
a215642828 Merge pull request #25364 from kamipo/fix_serialize_for_date_type
Fix `Type::Date#serialize` to return a date object correctly
2016-06-28 23:33:31 -03:00
Robin Dupret
eb1c0e2283 Tiny documentation fixes [ci skip]
Fix a tiny typo and vertical-align some return results in the
ActiveModel::Errors documentation.
2016-06-25 16:10:04 +02:00
Alex Kitchens
8305a09c5e [ci skip] Add additional documentation to ActiveModel::Errors 2016-06-22 15:45:11 -05:00
Alex Kitchens
92e8ede6df [ci skip] Remove duplicate alias documentation in ActiveModel::Validations 2016-06-16 09:15:44 -05:00
Ryuta Kamizono
10b81fb51a Fix Type::Date#serialize to return a date object correctly
Currently `Type::Date#serialize` does not cast a value to a date object.
It should be cast to a date object for finding by date column correctly
working.

Fixes #25354.
2016-06-16 08:04:16 +09:00
Sean Griffin
b3dfd7d16c Ensure that instances of ActiveModel::Errors can be marshalled
We now use default procs inside of the errors object, which gets
included by default when marshaling anything that includes
`ActiveModel::Validations`. This means that Active Record objects cannot
be marshalled. We strip and apply the default proc ourselves. This will
ensure the objects are YAML serializable as well, since YAML falls back
to marshal implementations now. This is less important, however, as the
errors aren't included when dumping Active Record objects.

This commit does not include a changelog entry, as 5.0 is still in RC
status at the time of writing, and 5.0.0 will not release with the bug
this fixes.

Fixes #25165
2016-05-30 14:04:29 -04:00
Raimo Tuisku
26fe640c9a Print the proper ::Float::INFINITY value when used as a default value
Addresses https://github.com/rails/rails/issues/22396
2016-05-23 20:54:43 -07:00
Jeremy Daer
89e2f7e722
Support for unified Integer class in Ruby 2.4+
Ruby 2.4 unifies Fixnum and Bignum into Integer: https://bugs.ruby-lang.org/issues/12005

* Forward compat with new unified Integer class in Ruby 2.4+.
* Backward compat with separate Fixnum/Bignum in Ruby 2.2 & 2.3.
* Drops needless Fixnum distinction in docs, preferring Integer.
2016-05-18 21:58:51 -07:00
Mohit Natoo
75c221f10f - removing redundant 'happens' in documentation [ci skip] 2016-05-19 02:02:30 +05:30
Vijay Dev
83ecf3fe56 Merge branch 'master' of github.com:rails/docrails
Conflicts:
	guides/source/configuring.md
2016-05-14 09:54:23 +00:00
Rafael Mendonça França
8ecc5ab1d8 Start Rails 5.1 development 🎉 2016-05-10 03:46:56 -03:00
Rafael Mendonça França
fbdcf5221a Preparing for 5.0.0.rc1 release 2016-05-06 16:54:40 -05:00
Christian Blais
17141481d9 Change RangeError to a more specific ActiveModel::RangeError
The should make it easier for apps to rescue ActiveModel specific
errors without the need to wrap all method calls with a generic
rescue RangeError.
2016-05-03 14:46:49 -04:00
Vipul A M
25f829e43f Add example for UnknownAttributeError
[ci skip]
2016-05-02 03:08:59 +05:30
Prathamesh Sonpatki
707b5c00ab
Active Model: Messages for strict validation always convert attributes to human readable form [ci skip] 2016-05-01 13:41:57 -05:00
lvl0nax
517cf249c3
Chomp: prefer String#chomp where we can for a clarity boost
Closes #24766, #24767

Signed-off-by: Jeremy Daer <jeremydaer@gmail.com>
2016-04-29 13:43:15 -07:00
eileencodes
f7a986012a Prep Rails 5 beta 4 2016-04-27 15:48:47 -05:00
Mohit Natoo
51d6a59329 - [ci skip] regardless is usually followed by of and not by if .. or not. 2016-04-21 00:04:05 +05:30
Bogdan Gusiev
80b9e5d7bd Fixed bug introduced in #24519. Makes build green again 2016-04-13 21:13:33 +03:00
Bogdan Gusiev
afb1f32e79 Use keyword arguments to cleanup without droping performance 2016-04-13 02:03:51 +03:00
Sen-Zhang
051d859880 prevent 'attribute_changed?' from returning nil 2016-04-11 19:33:52 -07:00
Jeremy Daer
20ffb63c2e Merge pull request #24511 from lihanli/activemodel-dirty-attribute-changed
speed up ActiveModel::Dirty#attribute_changed?
2016-04-11 15:14:44 -07:00
Lihan Li
73e2dbe651 set default parameter to nil to speed up attribute_changed?
Benchmark results:

Warming up --------------------------------------
            old code    32.176k i/100ms
            new code    34.837k i/100ms
Calculating -------------------------------------
            old code      1.595M (± 3.5%) i/s -      7.947M
            new code      1.942M (± 3.9%) i/s -      9.685M
2016-04-11 17:46:34 -04:00
Vipul A M
ac027338e4 Pass over all Rails 5 warnings, to make sure:
- we are ending sentences properly
- fixing of space issues
- fixed continuity issues in some sentences.

Reverts 8fc97d198e .
This change reverts making sure we add '.' at end of deprecation sentences.
This is to keep sentences within Rails itself consistent and with a '.' at the end.
2016-04-12 02:26:56 +05:30
PareshGupta
57f5f51bd2 fix length validation error typo 2016-04-07 15:37:17 +05:30
Prathamesh Sonpatki
7bdb4b5598 Allow passing record being validated to error message generator
- Pass object to I18n helper so that when calling message proc, it will
  pass that object as argument to the proc and we can generate custom
  error messages based on current record being validated.
- Based on https://github.com/rails/rails/issues/856.

[Łukasz Bandzarewicz, Prathamesh Sonpatki]
2016-04-05 12:55:02 +05:30
Kasper Timm Hansen
044baef101 Merge pull request #24299 from kitop/activemodel-errors-include-fix
Do not create a hash key when calling ActiveModel::Errors#include?
2016-03-25 13:24:41 +01:00
Sean Griffin
c7d3bd48df Apply scale before precision when coercing floats to decimal
Since precision is always larger than scale, it can actually change
rounding behavior. Given a precision of 5 and a scale of 3, when you
apply the precision of 5 to `1.25047`, the result is `1.2505`, which
when the scale is applied would be `1.251` instead of the expected
`1.250`.

This issue appears to only occur with floats, as scale doesn't apply to
other numeric types, and the bigdecimal constructor actually ignores
precision entirely when working with strings. There's no way we could
handle this for the "unknown object which responds to `to_d`" case, as
we can't assume an interface for applying the scale.

Fixes #24235
2016-03-24 16:09:19 -06:00
Esteban Pastorino
9848c4632f Do not create a hash key when calling ActiveModel::Errors#include?
From: https://github.com/rails/rails/issues/24279

Problem:
By doing `record.errors.include? :foo`, it adds a new key to the
@messages hash that defaults to an empty array.

This happens because of a combination of these 2 commits:
b97035df64
(Added in Rails 4.1)
and
6ec8ba16d8 (diff-fdcf8b65b5fb954372c6fe1ddf284c78R76)
(Rails 5.0)

By adding the default proc that returns an array for non-existing keys,
ruby adds that key to the hash.

Solution:
Change `#include?` to check with `has_key?` and then check if that value is
`present?`.

Add test case for ActiveModels::Errors#include?
2016-03-24 16:29:22 -04:00
ojab
3ece0d89d4 Use Range#cover? for Date inclusion validator 2016-03-24 11:36:07 +00:00
yuuji.yaginuma
163df5d6a0 use same name to type object
Follow up to #24079
2016-03-09 20:47:45 +09:00
eileencodes
826420b5fc Prep release for Rails 5 beta3 2016-02-24 10:27:02 -05:00
eileencodes
2c02bc0a47 Revert changes to validations from PR #18612
In order to fix issue #17621 we added a check to validations that
determined if a record should be validated. Based on the existing tests
and behavior we wanted we determined the best way to do that was by
checking if `!record.peristed? || record.changed? || record.marked_for_destruction?`

This change didn't make it into a release until now. When #23790 was
opened we realized that `valid?` and `invalid?` were broken and did not
work on persisted records because of the `!record.persisted?`.

While there is still a bug that #17621 brought up, this change was too
drastic and should not be a RC blocker. I will work on fixing this so
that we don't break `valid?` but also aren't validating parent records
through child records if that parent record is validate false. This
change removes the code changes to validate and the corresponding tests.
It adds tests for two of the bugs found since Rails 5 beta2 release.

Fixes #17621
2016-02-23 15:21:46 -05:00
Santiago Pastorino
e8d58bb299 Merge pull request #23743 from maclover7/rm-unused-parameter
Remove unused parameter from method
2016-02-21 21:45:22 -03:00
eileencodes
6f15b276cb Always validate record if validating a virtual attribute
Fixes #23645

When you're using an `attr_accessor` for a record instead of an
attribute in the database there's no way for the record to know if it
has `changed?` unless you tell it `attribute_will_change!("attribute")`.

The change made in 27aa4dd updated validations to check if a record was
`changed?` or `marked_for_destruction?` or not `persisted?`. It did not
take into account virtual attributes that do not affect the model's
dirty status.

The only way to fix this is to always validate the record if the
attribute does not belong to the set of attributes the record expects
(in `record.attributes`) because virtual attributes will not be in that
hash.

I think we should consider deprecating this particular behavior in the
future and requiring that the user mark the record dirty by noting that
the virtual attribute will change. Unfortunately this isn't easy because
we have no way of knowing that you did the "right thing" in your
application by marking it dirty and will get the deprecation warning
even if you are doing the correct thing.

For now this restores expected behavior when using a virtual attribute
by always validating the record, as well as adds tests for this case.

I was going to add the `!record.attributes.include?(attribute)` to the
`should_validate?` method but `uniqueness` cannot validate a virtual
attribute with nothing to hold on to the attribute. Because of this
`should_validate?` was about to become a very messy method so I decided
to split them up so we can handle it specifically for each case.
2016-02-20 09:15:39 -05:00
Jon Moss
67ba041a32 Remove unused parameter from method
The `attribute` parameter is not used inside the `normalize_detail`
method. This does not need to go through a deprecation cycle, since the
method is private.
2016-02-17 16:09:54 -05:00
Mehmet Emin İNAÇ
e38ced376f Add documentation about method to describe how it works [ci skip] 2016-02-04 20:03:24 +02:00
Sean Griffin
49f6ce63f3 Preparing for Rails 5.0.0.beta2 2016-02-01 14:37:52 -07:00
Aaron Patterson
6dfab475ca Merge branch '5-0-beta-sec'
* 5-0-beta-sec:
  bumping version
  fix version update task to deal with .beta1.1
  Eliminate instance level writers for class accessors
  allow :file to be outside rails root, but anything else must be inside the rails view directory
  Don't short-circuit reject_if proc
  stop caching mime types globally
  use secure string comparisons for basic auth username / password
2016-01-25 11:25:11 -08:00
Aaron Patterson
908c011395 bumping version 2016-01-25 10:22:15 -08:00
Aaron Patterson
4642d68d80 Eliminate instance level writers for class accessors
Instance level writers can have an impact on how the Active Model /
Record objects are saved.  Specifically, they can be used to bypass
validations.  This is a problem if mass assignment protection is
disabled and specific attributes are passed to the constructor.

CVE-2016-0753
2016-01-22 15:02:46 -08:00
Sean Griffin
302e92359c Refactor tz aware types, add support for PG ranges
This is an alternate implementation to #22875, that generalizes a lot of
the logic that type decorators are going to need, in order to have them
work with arrays, ranges, etc. The types have the ability to map over a
value, with the default implementation being to just yield that given
value. Array and Range give more appropriate definitions.

This does not automatically make ranges time zone aware, as they need to
be added to the `time_zone_aware` types config, but we could certainly
make that change if we feel it is appropriate. I do think this would be
a breaking change however, and should at least have a deprecation cycle.

Closes #22875.

/cc @matthewd
2016-01-08 14:11:45 -07:00
Andrey Novikov
0a0ffb64d8 Take UTC offset into account when assigning string value to time attribute. 2016-01-05 18:35:04 +03:00
Rashmi Yadav
1b608a695c Update copyright notices to 2016 [ci skip] 2015-12-31 18:27:19 +02:00
Robert Eshleman
57fb74e081 Convert non-Numeric values to Floats 2015-12-22 16:01:50 -05:00
Robert Eshleman
9c330798b0 Fix Regression in Numericality Validations
A regression (#22744) introduced in 7500dae caused certain numericality
validations to raise an error when run against an attribute with a
string value. Previously, these validations would successfully run
against string values because the value was cast to a numeric class.

This commit resolves the regression by converting string values to
floats before performing numericality comparison validations.

[fixes #22744]
2015-12-22 14:27:25 -05:00
eileencodes
7eae0bb88e Change alpha to beta1 to prep for release of Rails 5
🎉 🍻
2015-12-18 12:14:09 -05:00
Vokhmin Alexey V
61e5081404 ActiveRecord::Base#becomes should copy the errors 2015-12-14 19:02:20 +03:00
Sean Griffin
574f255629 Use a bind param for LIMIT and OFFSET
We currently generate an unbounded number of prepared statements when
`limit` or `offset` are called with a dynamic argument. This changes
`LIMIT` and `OFFSET` to use bind params, eliminating the problem.

`Type::Value#hash` needed to be implemented, as it turns out we busted
the query cache if the type object used wasn't exactly the same object.

This drops support for passing an `Arel::Nodes::SqlLiteral` to `limit`.
Doing this relied on AR internals, and was never officially supported
usage.

Fixes #22250.
2015-12-14 08:40:02 -07:00
Yasuo Honda
589cef086f Avoid dummy_time_value to add "2000-01-01" twice 2015-11-30 20:04:46 +00:00
Sean Griffin
de9b870f40 Merge pull request #21000 from twalpole/find_or_parameter_issues
Update and fix forbidden attributes test issues caused by AC::Parameters change
2015-11-23 14:58:05 -07:00
Yves Senn
96cc2e8335 Merge pull request #22333 from harrykiselev/patch-3
[ci skip] Update dirty.rb: documentation fix.
2015-11-21 11:21:20 +01:00
Harry V. Kiselev
ea0617e789 Update dirty.rb: documentation fix.
ActiveModel::Dirty module documentation fix.
2015-11-19 00:45:54 +03:00
Jerry D'Antonio
23b6f65fd1 Require only necessary concurrent-ruby classes. 2015-11-04 21:12:28 -05:00
Thomas Walpole
85f7d955f3 Update and fix forbidden attributes tests
Add AC::Parameters tests for WhereChain#not
2015-11-03 11:34:07 -08:00
Sean Griffin
328ec26cbe Merge pull request #19851 from repinel/numericality-validation2
Use the post-type-cast version of the attribute to validate numericality
2015-10-20 17:05:44 -06:00
Sean Griffin
d6919c524a All strings returned by ImmutableString should be frozen
I seriously don't even know why we handle booleans, but those strings
should technically be frozen. Additionally, we don't need to actually
check the class in the mutable string type, since the `cast_value`
function will always return a string.
2015-10-15 09:55:30 -07:00
Sean Griffin
34321e4a43 Add an immutable string type to opt out of string duping
This type adds an escape hatch to apps for which string duping causes
unacceptable memory growth. The reason we are duping them is in order to
detect mutation, which was a feature added to 4.2 in #15674. The string
type was modified to support this behavior in #15788.

Memory growth is really only a concern for string types, as it's the
only mutable type where the act of coersion does not create a new object
regardless (as we're usually returning an object of a different class).

I do feel strongly that if we are going to support detecting mutation,
we should do it universally for any type which is mutable. While it is
less common and ideomatic to mutate strings than arrays or hashes, there
shouldn't be rules or gotchas to understanding our behavior.

However, I also appreciate that for apps which are using a lot of string
columns, this would increase the number of allocations by a large
factor. To ensure that we keep our contract, if you'd like to opt out of
mutation detection on strings, you'll also be option out of mutation of
those strings.

I'm not completely married to the thought that strings coming out of
this actually need to be frozen -- and I think the name is correct
either way, as the purpose of this is to provide a string type which
does not detect mutation.

In the new implementation, I'm only overriding `cast_value`. I did not
port over the duping in `serialize`. I cannot think of a reason we'd
need to dup the string there, and the tests pass without it.
Unfortunately that line was introduced at a time where I was not nearly
as good about writing my commit messages, so I have no context as to
why I added it. Thanks past Sean. You are a jerk.
2015-10-15 09:50:37 -07:00
Roman Pramberger
e8c2f0bebe use ActiveModel::Naming module instead of Model [ci skip]
Use the documented module instead of ActiveModel::Model.
This makes the example more focused.
2015-10-06 10:46:14 +02:00
Sean Griffin
7e6d1f13b1 Merge pull request #21809 from yui-knk/fix_doc_am_serialization
[ci skip] Fix explanation of `ActiveModel::Serialization`
2015-10-02 09:40:53 -04:00
Guo Xiang Tan
7d0b1e4847 Fix AC::Parameters not being sanitized for query methods. 2015-10-02 16:26:16 +08:00
yui-knk
1fdb98c033 [ci skip] Fix explanation of ActiveModel::Serialization
This explanation was change by https://github.com/rails/rails/commit/7a27de2b.
This change reversed the including module (`ActiveModel::Serializers::JSON`)
and the included module (`ActiveModel::Serialization`) by mistake.
2015-10-02 13:20:19 +09:00
Pratik
1fb2092897 Fixed humane -> human [ci skip] 2015-09-26 00:51:46 +05:30
Sean Griffin
37661bfc81 validates_acceptance_of shouldn't require a database connection
The implementation of `attribute_method?` on Active Record requires
establishing a database connection and querying the schema. As a general
rule, we don't want to require database connections for any class macro,
as the class should be able to be loaded without a database (e.g. for
things like compiling assets).

Instead of eagerly defining these methods, we do it lazily the first
time they are accessed via `method_missing`. This should not cause any
performance hits, as it will only hit `method_missing` once for the
entire class.
2015-09-25 07:54:38 -06:00
Sean Griffin
136fc65c9b Improve the performance of save and friends
The biggest source of the performance regression in these methods
occurred because dirty tracking required eagerly materializing and type
casting the assigned values. In the previous commits, I've changed dirty
tracking to perform the comparisons lazily. However, all of this is moot
when calling `save`, since `changes_applied` will be called, which just
ends up eagerly materializing everything, anyway. With the new mutation
tracker, it's easy to just compare the previous two hashes in the same
lazy fashion.

We will not have aliasing issues with this setup, which is proven by the
fact that we're able to detect nested mutation.

Before:
    User.create! 2.007k (± 7.1%) i/s -     10.098k

After:
    User.create! 2.557k (± 3.5%) i/s -     12.789k

Fixes #19859
2015-09-24 14:06:59 -06:00
Sean Griffin
8e633e5058 Clean up the implementation of AR::Dirty
This moves a bit more of the logic required for dirty checking into the
attribute objects. I had hoped to remove the `with_value_from_database`
stuff, but unfortunately just calling `dup` on the attribute objects
isn't enough, since the values might contain deeply nested data
structures. I think this can be cleaned up further.

This makes most dirty checking become lazy, and reduces the number of
object allocations and amount of CPU time when assigning a value. This
opens the door (but doesn't quite finish) to improving the performance
of writes to a place comparable to 4.1
2015-09-24 14:06:59 -06:00
Kasper Timm Hansen
9c55ff564d Merge pull request #21218 from repinel/fix-as-callback-terminator
WIP: Fix the AS::Callbacks terminator regression from 4.2.3
2015-09-23 22:18:33 +02:00
Sean Griffin
66337b62ad Merge pull request #20317
AR: take precision into count when assigning a value to timestamp
attribute
2015-09-23 09:01:38 -06:00
Bogdan Gusiev
d03f519665 Fixed taking precision into count when assigning a value to timestamp attribute
Timestamp column can have less precision than ruby timestamp
In result in how big a fraction of a second can be stored in the
database.

  m = Model.create!
  m.created_at.usec == m.reload.created_at.usec
    # => false
    # due to different seconds precision in Time.now and database column

If the precision is low enough, (mysql default is 0, so it is always low
enough by default) the value changes when model is reloaded from the
database. This patch fixes that issue ensuring that any timestamp
assigned as an attribute is converted to column precision under the
attribute.
2015-09-23 13:29:08 +03:00
Roque Pinel
35cd365621 Fix the AS::Callbacks terminator regression from 4.2.3
Rails 4.2.3 AS::Callbacks will not halt chain if `false` is returned.
That is the behavior of specific callbacks like AR::Callbacks and
AM::Callbacks.
2015-09-22 22:32:56 -04:00
Akira Matsuda
d30f934af0 AMo typos 2015-09-22 23:36:40 +09:00
Sean Griffin
821d67cdf7 Require dependencies from stdlib in the Decimal type
In Active Record, it appears these were either autoloaded, which
actually was likely due to test ordering since the method `Float#to_d`
wouldn't trigger it. This makes it explicit, and unlikely to fail in the
future.
2015-09-21 10:36:45 -06:00
Sean Griffin
0e681c9f49 Remove no-op options being passed in AM type registrations
The `override` option is only a thing for Active Record registrations.
We should figure out how to make this properly error out without doing
anything too weird to the code.
2015-09-21 10:17:33 -06:00
Sean Griffin
858a7b0429 Move the appropriate type tests to the Active Model suite
Any tests for a type which is not overridden by Active Record, and does
not test the specifics of the attributes API interacting in more complex
ways have no reason to be in the Active Record suite. Doing this
revealed that the implementation of the date and time types in AM was
actually completely broken, and incapable of returning any value other
than `nil`.
2015-09-21 10:12:31 -06:00
Sean Griffin
4590d7729e Simplify the implementation of Active Model's type registry
Things like decorations, overrides, and priorities only matter for
Active Record, so the Active Model registry can be implemented much more
simply. At this point, I wonder if having Active Record's registry
inherit from Active Model's is even worth the trouble?

The Active Model class was also missing test cases, which have been
backfilled.

This removes the error when two types are registered with the same name,
but given that Active Model is meant to be significantly more generic, I
do not think this is an issue for now. If we want, we can raise an error
at the point that someone tries to register it.
2015-09-21 10:12:31 -06:00
Sean Griffin
22cc2b86f7 Various stylistic nitpicks
We do not need to require each file from AM individually, the type
module does that for us. Even if the classes are extremely small right
now, I'd rather keep any custom classes needed by AR in their own files,
as they can easily have more complex changes in the future.
2015-09-21 10:12:31 -06:00
Sean Griffin
e467deb6c6 TypeMap and HashLookupTypeMap shouldn't be in Active Model
These are used by the connection adapters to convert SQL type
information into the appropriate type object, and makes no sense outside
of the context of Active Record
2015-09-21 10:12:31 -06:00
Kir Shatrov
9cc8c6f373 Move ActiveRecord::Type to ActiveModel
The first step of bringing typecasting to ActiveModel
2015-09-21 10:12:13 -06:00
Jerry D'Antonio
56ac6e4768 Replaced ThreadSafe::Map with successor Concurrent::Map.
The thread_safe gem is being deprecated and all its code has been merged
into the concurrent-ruby gem. The new class, Concurrent::Map, is exactly
the same as its predecessor except for fixes to two bugs discovered
during the merge.
2015-09-19 09:56:26 -04:00
Akira Matsuda
dcecbb4234 File encoding is defaulted to utf-8 in Ruby >= 2.1 2015-09-18 17:05:05 +09:00
Dmitry Polushkin
e3d99e239d Validate multiple contexts on valid? and invalid? at once.
Example:

```ruby
class Person
  include ActiveModel::Validations

  attr_reader :name, :title
  validates_presence_of :name, on: :create
  validates_presence_of :title, on: :update
end

person = Person.new
person.valid?([:create, :update])    # => true
person.errors.messages               # => {:name=>["can't be blank"], :title=>["can't be blank"]}
```
2015-09-07 22:42:50 +01:00
Rafael Mendonça França
7b9b0b531f Revert "Merge pull request #21069 from dmitry/feature/validate-multiple-contexts-at-once"
This reverts commit 51dd2588433457960cca592d5b5dac6e0537feac, reversing
changes made to ecb4e4b21b3222b823fa24d4a0598b1f2f63ecfb.

This broke Active Record tests
2015-09-07 17:16:54 -03:00
Rafael Mendonça França
51dd258843 Merge pull request #21069 from dmitry/feature/validate-multiple-contexts-at-once
Validate multiple contexts on `valid?` and `invalid?` at once
2015-09-07 16:46:18 -03:00
Carlos Antonio da Silva
8ce0fdb5c4 Fix failure introduced by #17351 due to the new mocks implementation
It was not expecting the new `case_insensitive` option to be passed to
`generate_message`, instead of fixing the test we can just not pass this
option down since it is specific to the confirmation validator and not
necessary for the error message.
2015-09-01 08:53:29 -03:00
Jashank Jeremy
09f64873cd Fix syntax error introduced by #17351. 2015-09-01 19:11:26 +10:00
Rafael Mendonça França
57393957e1 Merge pull request #17351 from akshat-sharma/master
Add case_sensitive option for confirmation validation
2015-09-01 02:42:43 -03:00
Akshat Sharma
2438a1cf4e Add case_sensitive option for confirmation validation
Case :- 1. In case of email confirmation one needs case insensitive comparison
        2. In case of password confirmation one needs case sensitive comparison

[ci skip] Update Guides for case_sensitive option in confirmation validation
2015-09-01 10:42:51 +05:30
Robin Dupret
7a27de2bb0 Tiny documentation improvements [ci skip] 2015-08-28 15:33:48 +02:00
Gaurav Sharma
71ed339203 discard xml Serialization documentation that is no longer available [ci skip] 2015-08-22 04:06:14 +05:30
Marcin Olichwirowicz
3c6fc5892f Rename match_attribute_method? to matched_attribute_method
`match_attribute_method?` is a bit confusing because it suggest
that a return value is a boolean which is not true.
2015-08-12 00:23:12 +02:00
Zachary Scott
f7ebdb1ac5 Remove XML Serialization from core.
This includes the following classes:

- ActiveModel::Serializers::Xml
- ActiveRecord::Serialization::XmlSerializer
2015-08-07 11:01:48 -04:00
Dmitry Polushkin
86e3b047ba Validate multiple contexts on valid? and invalid? at once.
Example:

```ruby
class Person
  include ActiveModel::Validations

  attr_reader :name, :title
  validates_presence_of :name, on: :create
  validates_presence_of :title, on: :update
end

person = Person.new
person.valid?([:create, :update])    # => true
person.errors.messages               # => {:name=>["can't be blank"], :title=>["can't be blank"]}
```
2015-07-30 10:05:29 +01:00
schneems
5bb1d4d288 Freeze string literals when not mutated.
I wrote a utility that helps find areas where you could optimize your program using a frozen string instead of a string literal, it's called [let_it_go](https://github.com/schneems/let_it_go). After going through the output and adding `.freeze` I was able to eliminate the creation of 1,114 string objects on EVERY request to [codetriage](codetriage.com). How does this impact execution?

To look at memory:

```ruby
require 'get_process_mem'

mem = GetProcessMem.new
GC.start
GC.disable
1_114.times { " " }
before = mem.mb

after = mem.mb
GC.enable
puts "Diff: #{after - before} mb"

```

Creating 1,114 string objects results in `Diff: 0.03125 mb` of RAM allocated on every request. Or 1mb every 32 requests.

To look at raw speed:

```ruby
require 'benchmark/ips'

number_of_objects_reduced = 1_114

Benchmark.ips do |x|
  x.report("freeze")    { number_of_objects_reduced.times { " ".freeze } }
  x.report("no-freeze") { number_of_objects_reduced.times { " " } }
end
```

We get the results

```
Calculating -------------------------------------
              freeze     1.428k i/100ms
           no-freeze   609.000  i/100ms
-------------------------------------------------
              freeze     14.363k (± 8.5%) i/s -     71.400k
           no-freeze      6.084k (± 8.1%) i/s -     30.450k
```

Now we can do some maths:

```ruby
ips = 6_226k # iterations / 1 second
call_time_before = 1.0 / ips # seconds per iteration 

ips = 15_254 # iterations / 1 second
call_time_after = 1.0 / ips # seconds per iteration 

diff = call_time_before - call_time_after

number_of_objects_reduced * diff * 100

# => 0.4530373333993266 miliseconds saved per request
```

So we're shaving off 1 second of execution time for every 220 requests. 

Is this going to be an insane speed boost to any Rails app: nope. Should we merge it: yep. 

p.s. If you know of a method call that doesn't modify a string input such as [String#gsub](b0e2da69f0/lib/let_it_go/core_ext/string.rb (L37)) please [give me a pull request to the appropriate file](b0e2da69f0/lib/let_it_go/core_ext/string.rb (L37)), or open an issue in LetItGo so we can track and freeze more strings. 

Keep those strings Frozen

![](https://www.dropbox.com/s/z4dj9fdsv213r4v/let-it-go.gif?dl=1)
2015-07-19 17:45:10 -05:00
Guo Xiang Tan
beb07fbfae Revert "Revert "Reduce allocations when running AR callbacks.""
This reverts commit bdc1d329d4eea823d07cf010064bd19c07099ff3.

Before:
Calculating -------------------------------------
                        22.000  i/100ms
-------------------------------------------------
                        229.700  (± 0.4%) i/s -      1.166k
Total Allocated Object: 9939

After:
Calculating -------------------------------------
                        24.000  i/100ms
-------------------------------------------------
                        246.443  (± 0.8%) i/s -      1.248k
Total Allocated Object: 7939

```
begin
  require 'bundler/inline'
rescue LoadError => e
  $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
  raise e
end

gemfile(true) do
  source 'https://rubygems.org'
  # gem 'rails', github: 'rails/rails', ref: 'bdc1d329d4eea823d07cf010064bd19c07099ff3'
  gem 'rails', github: 'rails/rails', ref: 'd2876141d08341ec67cf6a11a073d1acfb920de7'
  gem 'arel', github: 'rails/arel'
  gem 'sqlite3'
  gem 'benchmark-ips'
end

require 'active_record'
require 'benchmark/ips'

ActiveRecord::Base.establish_connection('sqlite3::memory:')

ActiveRecord::Migration.verbose = false

ActiveRecord::Schema.define do
  create_table :users, force: true do |t|
    t.string :name, :email
    t.boolean :admin
    t.timestamps null: false
  end
end

class User < ActiveRecord::Base
  default_scope { where(admin: true) }
end

admin = true

1000.times do
  attributes = {
    name: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    email: "foobar@email.com",
    admin: admin
  }

  User.create!(attributes)

  admin = !admin
end

GC.disable

Benchmark.ips(5, 3) do |x|
  x.report { User.all.to_a }
end

key =
  if RUBY_VERSION < '2.2'
    :total_allocated_object
  else
    :total_allocated_objects
  end

before = GC.stat[key]
User.all.to_a
after = GC.stat[key]
puts "Total Allocated Object: #{after - before}"
```
2015-07-16 01:02:15 +08:00
Roque Pinel
7500daec69 Conditionally convert the raw_value received by the numeric validator.
This fixes the issue where you may be comparing (using a numeric
validator such as `greater_than`) numbers of a specific Numeric type
such as `BigDecimal`.

Previous behavior took the numeric value to be validated and
unconditionally converted to Float. For example, due to floating point
precision, this can cause issues when comparing a Float to a BigDecimal.

Consider the following:

```
    validates :sub_total, numericality: {
      greater_than: BigDecimal('97.18')
    }
```

If the `:sub_total` value BigDecimal.new('97.18') was validated against
the above, the following would be valid since `:sub_total` is converted
to a Float regardless of its original type. The result therefore becomes
Kernel.Float(97.18) > BigDecimal.new('97.18')

The above illustrated behavior is corrected with this patch by
conditionally converting the value to validate to float.

Use the post-type-cast version of the attribute to validate numericality

[Roque Pinel & Trevor Wistaff]
2015-07-11 14:40:14 -04:00
Yves Senn
4cc5917dce docs, clarify the meanaing of return values from validation methods.
[ci skip]

Closes #20792.

Custom validation methods are implemented in terms of
callbacks. The `validate` callback chain can't be halted using return
values of individual callbacks.
2015-07-07 14:39:58 +02:00
Yves Senn
b8962664ad docs, remove accidental :nodoc: of ActiveModel::Validations::ClassMethods methods.
[ci skip]

While this :nodoc: did hide the constant it also removed the following
methods from the API docs:

- #attribute_method?
- #clear_validators!
- #validate
- #validators
- #validators_on

Those are public API and should be visible.

Issue was caused by dee4fbc

/cc @zzak
2015-07-07 14:16:03 +02:00
Robin Dupret
bc71e43252 Separate the constraint and other options [ci skip]
Only one constraint option can be used at a time (except for the minimum
and maximum ones that can eventually be combined). However, other
options can be used with them (e.g. the validation failure message).
So let's make the distinction between these two different options
categories.

[Yves Senn, Matthew Draper & Robin Dupret]
2015-07-01 16:20:07 +02:00
Radan Skoric
e5a78aaaf8 Improve Validation Helpers' documentation comments and tests 2015-06-27 16:34:16 +02:00
Robin Dupret
e09129c94c A few documentation fixes [ci skip] 2015-06-23 17:55:37 +02:00
Mehmet Emin İNAÇ
5b36015830 Add nodoc to the Validations::Helpers [ci skip] 2015-06-22 20:06:42 +03:00
Yves Senn
ebc4c607a7 docs, ✂️ wrongly placed heading. [ci skip]
The heading "Active Model Length Validator" was shown on the
"ActiveModel::Validations" page without any text following it.
2015-06-22 15:52:47 +02:00
Roque Pinel
bfd4e6a0bc Move the validations HelperMethods to its own file
Closes #11209

[Roque Pinel & Steven Yang]
2015-06-21 19:56:53 -04:00
Rafael Mendonça França
96bb004fc6 Revert "Add code example for include option of AM::Serialization#serializable_hash"
This reverts commit 3d949f34816d6eca0a6b59cfa08d91f36e8e64dd.

This was already documented in other PR.
2015-06-10 08:50:39 -03:00
Radan Skoric
3d949f3481 Add code example for include option of AM::Serialization#serializable_hash 2015-06-09 17:41:14 -03:00
Robin Dupret
b10c3866d7 Tiny documentation edits [ci skip] 2015-06-07 16:01:09 +02:00
Robin Dupret
911f189f88 Merge pull request #20004 from rusikf/patch-1
add docs to include option at ActiveModel::Serialization [ci skip]
2015-06-07 15:53:53 +02:00
unknown
3833d4529f formatting changes 2015-05-29 16:27:23 -04:00
rusikf
47896b3d08 add docs to include option at ActiveModel::Serialization#serializable_hash [ci skip] 2015-05-11 13:10:30 +03:00
Gourav Tiwari
6b557ae709 minor rdoc syntax fix [ci skip] 2015-05-08 14:45:32 -07:00
Zamith
6f418a09d8
Adds/Corrects use case for adding an error message
I believe this is a use case that was supposed to be supported, and it's
a small fix.
2015-05-04 13:36:26 +01:00
Jay Elaraj
b2967999ae ensure method_missing called for non-existing methods passed to
`ActiveModel::Serialization#serializable_hash`
2015-04-28 21:06:30 -04:00
Zachary Scott
dee4fbc90b Don't document private internal constant [ci skip] 2015-04-26 15:47:29 -07:00
Tim Wade
f207d948c8
Fix grammar/style: assigns/declares -> assignments/declarations.
[ci skip]
2015-04-24 09:02:38 -04:00
Tim Wade
ed6de3afcc
Fix grammar/style: use (v) fall back (on).
[ci skip]
2015-04-24 08:52:51 -04:00
Tim Wade
37349f71ad
Fix grammar/style: break up long sentence.
A conjunction was needed to make these sentences correct. Breaking them
up seemed like a better option.

[ci skip]
2015-04-24 08:40:41 -04:00
Tim Wade
875f675284
Fix grammar/style: pluralize 'each of its method'
[ci skip]
2015-04-24 08:32:58 -04:00
Fernando Tapia Rico
f072db8e4f Add ActiveModel::Dirty#[attr_name]_previously_changed? and
`ActiveModel::Dirty#[attr_name]_previous_change` to improve access
to recorded changes after the model has been saved.

It makes the dirty-attributes query methods consistent before and after
saving.
2015-04-21 19:30:46 +02:00
Rafael Mendonça França
c539cc0061 Merge pull request #19448 from tgxworld/fix_activesupport_callbacks_clash_on_run
Fix AS::Callbacks raising an error when `:run` callback is defined.
2015-04-06 18:58:19 -03:00
Yves Senn
70b7e281de fix typo in deprecation message. [Robin Dupret] 2015-04-05 17:23:36 +02:00
Guillermo Iguaran
151aa690a2 Merge pull request #19594 from radar/require-module-delegation
Require Module#delegate core ext in ActiveModel::Naming
2015-03-30 19:56:57 -05:00
Ryan Bigg
b6bf58c220 Require Module#delegate core ext in ActiveModel::Naming 2015-03-31 11:41:16 +11:00
Rafael Mendonça França
7131f6ba22 Merge pull request #19021 from morgoth/activemodel-errors-refactoring
Simplify and alias ActiveModel::Errors methods where possible
2015-03-30 13:47:30 -03:00
Sean Griffin
1c341eb7cb Deprecate the :tokenizer option to validates_length_of
As demonstrated by #19570, this option is severely limited, and
satisfies an extremely specific use case. Realistically, there's not
much reason for this option to exist. Its functionality can be trivially
replicated with a normal Ruby method. Let's deprecate this option, in
favor of the simpler solution.
2015-03-29 16:34:01 -06:00
Radan Skoric
26b35a4096 Fix ActiveModel::Errors#delete return value to stay backward compatible
Rails 5.0 changes to ActiveModel::Errors include addition of `details`
that also accidentally changed the return value of `delete`. Since
there was no test for that behavior it went unnoticed. This commit
adds a test and fixes the regression.

Small improvements to comments have also been made. Since `get` is
getting deprecated it is better to use `[]` in other methods' code
examples. Also, in the module usage example, `def Person.method`
was replaced with a more commonly used `def self.method` code style.
2015-03-22 23:18:22 +01:00
Guo Xiang Tan
bdc1d329d4 Revert "Reduce allocations when running AR callbacks."
This reverts commit 796cab45561fce268aa74e6587cdb9cae3bb243e.
2015-03-22 11:21:02 +08:00
Radan Skoric
cf7fac7e29 Fix ActiveModel::Errors deprecation messages failing when used on its own
Deprecation messages in ActiveModel::Errors are using String#squish
from ActiveSupport but were not explicitly requiring it, causing failures
when used outside rails.
2015-03-21 12:35:25 +01:00
Melanie Gilman
9034938714 Fix spelling error in has_secure_password documentation [ci skip] 2015-03-03 20:05:02 -05:00
Sean Griffin
c0584ea034 Merge pull request #19077 from robin850/unknown-attribute-error
Move `UnknownAttributeError` to a more sane namespace
2015-03-02 09:21:42 -07:00
Vipul A M
cdaab2c479 Removed non-standard and unused require 'active_support/deprecation' from parts out of active_support. 2015-02-27 23:20:09 +05:30
Robin Dupret
95c2fc9679 Follow-up to #10776
The name `ActiveModel::AttributeAssignment::UnknownAttributeError` is
too implementation specific so let's move the constant directly under
the ActiveModel namespace.

Also since this constant used to be under the ActiveRecord namespace, to
make the upgrade path easier, let's avoid raising the former constant
when we deal with this error on the Active Record side.
2015-02-26 15:40:03 +01:00
Ian Ker-Seymer
c5d62cb86d activemodel: make .model_name json encodable
Previously, calling `User.model_name.to_json` would result in an infinite
recursion as `.model_name` inherited its `.as_json` behavior from Object. This
patch fixes that unexpected behavior by delegating `.as_json` to :name.
2015-02-24 11:00:32 -07:00
Rafael Mendonça França
f55bfe7260 Change the deprecation messages to show the preferred way to work with
ActiveModel::Errors
2015-02-20 20:58:58 -02:00
Wojciech Wnętrzak
9ebb778ca0 Simplify and alias ActiveModel::Errors methods where possible 2015-02-20 21:42:00 +01:00
Lucas Mazza
830b7041f2 Move the validate! method to ActiveModel::Validations. 2015-02-20 16:05:26 -02:00
Rafael Mendonça França
e0f29c51b9 Merge pull request #17144 from skojin/patch-doc-validation-format-z-regexp
fix mistype in doc about \z regexp
2015-02-20 14:30:47 -02:00
yuuji.yaginuma
66e2e19bc0 use messages instead of deprecated ActiveModel::Errors#[]= method [ci skip] 2015-02-20 23:53:36 +09:00
Yves Senn
259d33db8c Merge pull request #18996 from morgoth/deprecate-more-errors-methods
Deprecate `ActiveModel::Errors` `add_on_empty` and `add_on_blank` methods
2015-02-19 14:16:47 +01:00
Wojciech Wnętrzak
fd38838f29 Deprecate ActiveModel::Errors add_on_empty and add_on_blank methods
without replacement.
2015-02-19 14:10:38 +01:00
Rafael Mendonça França
3c750c4c6c Merge pull request #18634 from morgoth/deprecate-some-errors-methods
Deprecate `ActiveModel::Errors` `get`, `set` and `[]=` methods.
2015-02-18 18:58:28 -02:00
Robin Dupret
1747c4e2ce Tiny documentation edits [ci skip] 2015-02-15 19:19:04 +01:00
Vijay Dev
95546d4935 Merge branch 'master' of github.com:rails/docrails 2015-02-14 15:35:47 +00:00
Rafael Mendonça França
7919c29d50 Merge pull request #16381 from kakipo/validate-length-tokenizer
Allow symbol as values for `tokenizer` of `LengthValidator`
2015-02-13 12:09:36 -02:00
Rafael Mendonça França
16809025fe Merge pull request #18388 from claudiob/better-docs-for-active-model-lint-tests
Better docs for AM::Lint::Tests
2015-02-06 11:06:59 -02:00
Xavier Noria
6f8d9bd6da revises AM:Dirty example [Godfrey Chan & Xavier Noria]
The existing example seems somewhat forced: is it realistic
to have a model that accepts state in its initializer but
considers it has not been changed? By allowing state changes
to happen only via accessors it seems more natural that new
instances are considered to be unchanged (as they are in AR).

[ci skip]
2015-02-06 10:29:05 +01:00
Xavier Noria
a2af7bb928 use parentheses here, for the beard of the Prophet! [ci skip] 2015-02-06 09:45:24 +01:00
Xavier Noria
4af4cead15 applies guidelines to dirty.rb [ci skip] 2015-02-06 09:36:28 +01:00
Carlos Antonio da Silva
f44b437627 Wrap method arguments with parentheses in docs
As per Rails general coding conventions. Related to #18794 [ci skip]
2015-02-03 07:35:11 -02:00
Vipul A M
fc87123fe8 Person class doesn't contain finder methods, hence usage of Person.find_by is wrong.
Added simple initialize and made use of Person.new instead of Person.find_by to clarify the docs.
[ci skip]
2015-02-03 12:09:42 +05:30
eileencodes
27aa4dda7d Fix validations on child record when record parent has validate: false
Fixes #17621. This 5 year old (or older) issue causes validations to fire
when a parent record has `validate: false` option and a child record is
saved. It's not the responsibility of the model to validate an
associated object unless the object was created or modified by the
parent.

Clean up tests related to validations

`assert_nothing_raised` is not benefiting us in these tests
Corrected spelling of "respects"
It's better to use `assert_not_operator` over `assert !r.valid`
2015-02-01 16:03:49 -08:00
Carlos Antonio da Silva
fdeef19833 Move required error message and changelog to Active Record
The new association error belongs to Active Record, not Active Model.
See #18700 for reference.
2015-02-01 10:31:54 -02:00
Wojciech Wnętrzak
6ec8ba16d8 Deprecate ActiveModel::Errors get, set and []= methods.
They have inconsistent behaviour currently.
2015-02-01 13:14:00 +01:00
Vipul A M
0f67f00d94 AM#Dirty doc fixes
- Grammar fixes
- Add doc for changes_include?
-  implemntations => implementations
2015-02-01 13:43:35 +05:30
Vipul A M
db41078566 Fix description for AM::Callbacks 2015-01-31 11:59:02 +05:30
Henrik Nygren
9a6c6c6f09 Provide a better error message on :required association
Fixes #18696.
2015-01-28 11:32:10 +02:00
Yves Senn
c8e39e2fd4 Merge pull request #18670 from morgoth/fix-duplicating-errors-details
Fixed duplicating ActiveModel::Errors#details
2015-01-24 15:08:11 +01:00
Wojciech Wnętrzak
fb7d95b212 Fixed duplicating ActiveModel::Errors#details 2015-01-24 11:58:55 +01:00
Eugene Gilburg
5bdb42159e use attribute assignment module logic during active model initialization 2015-01-23 14:42:47 -08:00
Sean Griffin
a225d4bec5 ✂️ and 💅 for #10776
Minor style changes across the board. Changed an alias to an explicit
method declaration, since the alias will not be documented otherwise.
2015-01-23 14:51:59 -07:00
Bogdan Gusiev
2606fb3397 Extracted ActiveRecord::AttributeAssignment to ActiveModel::AttributesAssignment
Allows to use it for any object as an includable module.
2015-01-23 23:43:22 +02:00
Rafael Mendonça França
14599a5758 Merge pull request #18322 from morgoth/add-error-codes
Add ActiveModel::Errors#codes
2015-01-21 14:28:54 -02:00
Wojciech Wnętrzak
2ee6ed69fc Add missing AS core extension dependency 2015-01-21 08:04:40 +01:00
Wojciech Wnętrzak
cb74473db6 Add ActiveModel::Errors#details
To be able to return type of validator, one can now call `details`
on Errors instance:

```ruby
class User < ActiveRecord::Base
  validates :name, presence: true
end
```

```ruby
user = User.new; user.valid?; user.errors.details
=> {name: [{error: :blank}]}
```
2015-01-20 22:33:42 +01:00
Sean Griffin
ea721d7027 Don't calculate in-place changes on attribute assignment
When an attribute is assigned, we determine if it was already marked as
changed so we can determine if we need to clear the changes, or mark it
as changed. Since this only affects the `attributes_changed_by_setter`
hash, in-place changes are irrelevant to this process. Since calculating
in-place changes can be expensive, we can just skip it here.

I also added a test for the only edge case I could think of that would
be affected by this change.
2015-01-18 13:43:31 -07:00
Sean Griffin
72570ea289 Merge pull request #18439 from mokhan/validates-acceptance-of-array
allow '1' or true for acceptance validation.
2015-01-12 12:06:00 -07:00
Anton Davydov
095b92af6c Fix error messages scope [skip ci] 2015-01-12 18:21:56 +03:00
mo khan
140557e85f allow '1' or true for acceptance validation. 2015-01-10 22:47:47 -07:00
robertomiranda
e0213f45ea Remove attributes_protected_by_default reference, since MassAssignmentSecurity was removed from ActiveModel f8c9a4d3e88181 2015-01-09 17:53:54 -05:00
claudiob
76dc58b4d0 Better docs for AM::Lint::Tests
This commit changes the original documentation of ActiveModel::Lint::Tests
introduced in dbf20c2d to focus less on *why* the tests exist and more on
*what* the tests do.

For instance, `test_to_key` was documented as:

> Returns an Enumerable of all (primary) key attributes...

whereas `test_to_key` is simply a test meant to *fail* or *pass*, and the
documentation above refers to `to_key`.

[ci skip]
2015-01-07 09:15:47 -08:00
George Millo
fc933fd4ab removing unecessary parameter in private method
'_singularize' only ever gets called with one argument
2015-01-06 00:10:56 +00:00
Rafael Mendonça França
bf7b8c193f Remove unneeded requires
These requires were added only to change deprecation message
2015-01-04 12:11:03 -03:00
Rafael Mendonça França
37175a24bd Remove deprecated ActiveModel::Dirty#reset_#{attribute} and ActiveModel::Dirty#reset_changes. 2015-01-04 11:58:42 -03:00
Rafael Mendonça França
4591b0fc04 Merge pull request #17227 from claudiob/explicitly-abort-callbacks
Introduce explicit way of halting callback chains by throwing :abort. Deprecate current implicit behavior of halting callback chains by returning `false` in apps ported to Rails 5.0. Completely remove that behavior in brand new Rails 5.0 apps.

Conflicts:
	railties/CHANGELOG.md
2015-01-03 17:22:20 -03:00
Vijay Dev
4b9dba99d6 Merge branch 'master' of github.com:rails/docrails 2015-01-03 14:58:17 +00:00
claudiob
91b8129320 Deprecate false as the way to halt AM callbacks
Before this commit, returning `false` in an ActiveModel `before_` callback
such as `before_create` would halt the callback chain.

After this commit, the behavior is deprecated: will still work until
the next release of Rails but will also display a deprecation warning.

The preferred way to halt a callback chain is to explicitly `throw(:abort)`.
2015-01-02 15:31:56 -08:00
claudiob
f767981286 Deprecate false as the way to halt AM validation callbacks
Before this commit, returning `false` in an ActiveModel validation
callback such as `before_validation` would halt the callback chain.

After this commit, the behavior is deprecated: will still work until
the next release of Rails but will also display a deprecation warning.

The preferred way to halt a callback chain is to explicitly `throw(:abort)`.
2015-01-02 15:31:56 -08:00
claudiob
2386daabe7 Throw :abort halts default CallbackChains
This commit changes arguments and default value of CallbackChain's :terminator
option.

After this commit, Chains of callbacks defined **without** an explicit
`:terminator` option will be halted as soon as a `before_` callback throws
`:abort`.

Chains of callbacks defined **with** a `:terminator` option will maintain their
existing behavior of halting as soon as a `before_` callback matches the
terminator's expectation. For instance, ActiveModel's callbacks will still
halt the chain when a `before_` callback returns `false`.
2015-01-02 15:31:55 -08:00
claudiob
7cc145ec65 Use Active Model, not ActiveModel in plain English
Also prevents the word "Model" from linking to the documentation
of ActiveModel::Model because that's not intended.

[ci skip]
2015-01-02 14:19:21 -08:00
Arun Agrawal
4de18d0ead Update copyright notices to 2015 [ci skip] 2014-12-31 08:34:14 +01:00
Rohit Arondekar
a928928c96 Use more semantic method to check password 2014-12-30 21:27:46 +05:30
Sean Griffin
18ae0656f5 Don't calculate all in-place changes to determine if attribute_changed?
Calling `changed_attributes` will ultimately check if every mutable
attribute has changed in place. Since this gets called whenever an
attribute is assigned, it's extremely slow. Instead, we can avoid this
calculation until we actually need it.

Fixes #18029
2014-12-22 14:55:58 -07:00
Robson Marques
ebaf4e40cd Fix inaccurate docs in active_model errors [ci skip]
The default value for the argument `message` in
`ActiveModel::Errors#add` has a new behavior
since ca99ab2481d44d67bc392d0ec1125ff1439e9f94.

Before
  person.errors.add(:name, nil)
  # => ["is invalid"]

After
  person.errors.add(:name, nil)
  # => [nil]
2014-12-22 09:06:30 -02:00
Godfrey Chan
4a19b3dea6 Pass through the prepend option to AS::Callback
I'm not sure what's the use case for this, but apparently it broke some apps.
Since it was not the intended result from #16210 I fixed it to not raise an
exception anymore. However, I didn't add documentation for it because I don't
know if this should be officially supported without knowing how it's meant to
be used.

In general, validations should be side-effect-free (other than adding to the
error message to `@errors`). Order-dependent validations seems like a bad idea.

Fixes #18002
2014-12-12 14:51:02 -08:00
_tiii
a4b02be067 add brackets around attribute_name
since 'attr_name_will_change!' is not an actual method it should
be clearer that you have to insert the attribute name as in line 104

[ci skip]
2014-12-08 17:39:29 +01:00
Sean Griffin
d1f003e67b Correctly handle multiple attribute method prefix/suffixes which match
Active Record defines `attribute_method_suffix :?`. That suffix will
match any predicate method when the lookup occurs in Active Model. This
will make it incorrectly decide that `id_changed?` should not exist,
because it attempts to determine if the attribute `id_changed` is
present, rather than `id` with the `_changed?` suffix. Instead, we will
look for any correct match.
2014-12-04 15:50:31 -07:00
Sean Griffin
704c658531 Ensure numericality validations work with mutation
The detection of in-place changes caused a weird unexpected issue with
numericality validations. That validator (out of necessity) works on the
`_before_type_cast` version of the attribute, since on an `:integer`
type column, a non-numeric string would type cast to 0.

However, strings are mutable, and we changed strings to ensure that the
post type cast version of the attribute was a different instance than
the before type cast version (so the mutation detection can work
properly).

Even though strings are the only mutable type for which a numericality
validation makes sense, special casing strings would feel like a strange
change to make here. Instead, we can make the assumption that for all
mutable types, we should work on the post-type-cast version of the
attribute, since all cases which would return 0 for non-numeric strings
are immutable.

Fixes #17852
2014-12-01 05:31:44 -07:00
Rafael Mendonça França
f25ad07f5a Start Rails 5 development 🎉
We will support only Ruby >= 2.1.

But right now we don't accept pull requests with syntax changes to drop
support to Ruby 1.9.
2014-11-28 15:00:06 -02:00