Commit Graph

1803 Commits

Author SHA1 Message Date
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
Matthew Draper
d6f2000a67 Wrangle the asset build into something that sounds more general 2016-02-01 05:03:03 +10:30
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
Lachlan Sylvester
4ba66ef108 remove activemodel dependency on builder 2016-01-06 18:55:59 +11:00
Rafael Mendonça França
53954aa476 Move CHANGELOG entry to Active Record
While the type definition is in Active Model the change of behavior will
be only user facing in Active Record so better to put the entry in its
changelog.

[ci skip]
2016-01-05 23:00:57 -02: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
Robert Eshleman
b96fdd234d Failing Tests for Validating String Numbericality
Covers Regressions:

* <=
* <
* ==
* >
* >=
* other than
2015-12-22 14:27:25 -05:00
Genadi Samokovarov
c5b6ec7b0f No more no changes entries in the CHANGELOGs
During the `5.0.0.beta1` release, the CHANGELOGs got an entry like the
following:

```
* No changes.
```

It is kinda confusing as there are indeed changes after it. Not a
biggie, just a small pass over the CHANGELOGs.

[ci skip]
2015-12-21 11:46:38 +02:00
Jon Atack
d3e98c6f30 Add missing @claudiob credit to change log [skip ci] 2015-12-20 22:03:53 +01:00
eileencodes
099ddfdefd Add CHANGELOG headers for Rails 5.0.0.beta1 2015-12-18 15:58:25 -05:00
eileencodes
7eae0bb88e Change alpha to beta1 to prep for release of Rails 5
🎉 🍻
2015-12-18 12:14:09 -05:00
Rafael França
b7a7e82207 Merge pull request #22598 from yui-knk/deprecate_string_callback
Deprecate passing string to define callback.
2015-12-16 13:54:02 -02:00
yui-knk
21f4017fd9 Deprecate passing string to define callback. 2015-12-16 19:56:20 +09: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
Aaron Patterson
2de7385cef Merge pull request #22381 from yahonda/use_adapter_subsecond_precision_supported
Use adapter supports_datetime_with_precision
2015-12-13 12:13:22 +09:00
Rafael França
bf9facb31c Merge pull request #22517 from Elektron1c97/master
[ci skip] Add a dollar sign to each command in the READMEs
2015-12-07 01:07:09 -02:00
Elektron1c97
6bd417df50 [ci skip] Add a dollar sign to each command in the READMEs
According to pr #22443 in the guides there's always a dollar sign before every command, so why is in the main README a `$` and in every submodule a `%`?

Just eye candy..
2015-12-06 19:18:52 +01:00
keepcosmos
7a8031b578 add test for nested model translation 2015-12-03 14:37:05 +09:00
Yasuo Honda
589cef086f Avoid dummy_time_value to add "2000-01-01" twice 2015-11-30 20:04:46 +00:00
Sean Griffin
c78c43533e Fix test failures caused by #21000 2015-11-23 15:19:39 -07: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
0d216d1add Really fix test failures caused by #19851
Ok, this explains why the branch showed as green. We don't run files in
isolation for PRs, only for master. Active Support monkeypatches
`BigDecimal#to_s`, so the generated error message was different
depending on if the file was run in isolation
2015-10-20 18:08:50 -06:00
Sean Griffin
12df3391e3 Fix test failures caused by #19851
The error message when asserting `greater_than: BigDecimal.new` will
give an error message based on how BigDecimal displays itself. Big
decimal appears to always use scientific notation. This might not be the
best error message for the general case, but the general case wouldn't
use big decimal for the validation. And if they do, they likely need
this level of precision.
2015-10-20 17:49:47 -06: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
Roque Pinel
e2b3ccd1aa Refactor AS::Callbacks halt config and fix the documentation
Move from `AS::Callbacks::CallbackChain.halt_and_display_warning_on_return_false`
to `AS::Callbacks.halt_and_display_warning_on_return_false` base on
[this
discussion](https://github.com/rails/rails/pull/21218#discussion_r39354580)

Fix the documentation broken by 0a120a818d413c64ff9867125f0b03788fc306f8
2015-10-01 13:04:20 -04: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
dac7d0d046 Fix another implicit dependency of the AM test suite
Hopefully this is the last one
2015-09-21 10:50:36 -06: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
Semyon Pupkov
aef6b79967 Fix typo in activemodel changelog 2015-09-08 23:37:17 +05: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
Prakash Laxkar
3ee1f7b40b Removed unused config file 2015-09-03 08:40:03 +05:30
Aditya Kapoor
69f3f81e6c Add missing test for #17351 2015-09-01 17:35:50 +05:30
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
Ronak Jangir
8d7bf97798 Removed duplicate requiring minitest/mock as it is already required in method_call_assertions 2015-08-26 19:43:54 +05:30
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
yuuji.yaginuma
0a20e48d52 pass the correct argument to mock on a test of validates_length_of 2015-07-28 22:59:42 +09: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
Zamith
a9ab7e85fd Removes unnecessary comments from i18n validations tests [ci skip]
These comments do not add a lot to the readability, grepability or
overall understanding of the tests, therefore I believe they can be
safely removed.
2015-07-11 12:29:46 +01:00
Zamith
ec7771e7f6 Remove the reference to mocha in activemodel
Activemodel is no longer dependent on mocha, so we can make the comments
more generic.
2015-07-11 02:08:45 +01:00
Kasper Timm Hansen
8a389ffc10 Use private method call assertions in Active Model tests.
Also fix Minitest constant reference.
2015-07-10 23:45:42 +02:00
Rafael Mendonça França
f6f3772c17 Merge pull request #20803 from TheBlasfem/marking_serialization_class
marking serialization class in Readme
2015-07-08 00:45:37 -03:00
Julio Lopez
a18b24f71f marking serialization class 2015-07-07 21:58:22 -05: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
Yves Senn
9946788775 select the AR adapter through bin/test. 2015-06-11 14:24:56 +02:00
Yves Senn
54d84cbb77 use our runner (bin/test) for framework components.
This adds a script `bin/test` to most Rails framework components. The
script uses the rails minitest plugin to augment the runner.
See https://github.com/rails/rails/pull/19571 for details about the
plugin.

I did not yet add `bin/test` for activerecord, activejob and railties.
These components rely on specific setup performed in the rake-tasks.
2015-06-11 14:12:15 +02: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
Anton Davydov
3f92a8247c Fix typo in AM I18n validation test name [skip ci] 2015-06-09 01:23:20 +03:00