railties 3.0.0.beta4 → 3.0.0.rc
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG +24 -6
- data/README.rdoc +25 -0
- data/guides/assets/javascripts/code_highlighter.js +0 -0
- data/guides/assets/javascripts/guides.js +0 -0
- data/guides/assets/stylesheets/print.css +0 -0
- data/guides/assets/stylesheets/reset.css +0 -0
- data/guides/assets/stylesheets/style.css +0 -0
- data/guides/source/3_0_release_notes.textile +5 -3
- data/guides/source/action_controller_overview.textile +19 -0
- data/guides/source/active_record_basics.textile +27 -21
- data/guides/source/active_record_querying.textile +39 -37
- data/guides/source/{activerecord_validations_callbacks.textile → active_record_validations_callbacks.textile} +30 -29
- data/guides/source/active_support_core_extensions.textile +232 -107
- data/guides/source/api_documentation_guidelines.textile +187 -0
- data/guides/source/association_basics.textile +45 -1
- data/guides/source/configuring.textile +7 -7
- data/guides/source/contributing_to_rails.textile +42 -15
- data/guides/source/form_helpers.textile +1 -1
- data/guides/source/generators.textile +37 -37
- data/guides/source/getting_started.textile +11 -11
- data/guides/source/i18n.textile +1 -1
- data/guides/source/index.html.erb +14 -6
- data/guides/source/initialization.textile +130 -124
- data/guides/source/layout.html.erb +5 -2
- data/guides/source/layouts_and_rendering.textile +2 -2
- data/guides/source/migrations.textile +4 -3
- data/guides/source/plugins.textile +15 -15
- data/guides/source/rails_application_templates.textile +2 -2
- data/guides/source/routing.textile +83 -62
- data/guides/source/security.textile +2 -2
- data/guides/w3c_validator.rb +30 -6
- data/lib/rails.rb +3 -3
- data/lib/rails/application.rb +43 -19
- data/lib/rails/application/bootstrap.rb +2 -0
- data/lib/rails/application/configuration.rb +3 -3
- data/lib/rails/application/finisher.rb +6 -6
- data/lib/rails/cli.rb +1 -19
- data/lib/rails/commands.rb +5 -5
- data/lib/rails/commands/application.rb +1 -1
- data/lib/rails/commands/console.rb +1 -4
- data/lib/rails/commands/generate.rb +0 -0
- data/lib/rails/commands/plugin.rb +57 -52
- data/lib/rails/commands/runner.rb +2 -1
- data/lib/rails/commands/server.rb +6 -2
- data/lib/rails/configuration.rb +2 -3
- data/lib/rails/console/app.rb +0 -2
- data/lib/rails/engine.rb +14 -15
- data/lib/rails/engine/configuration.rb +5 -5
- data/lib/rails/generators.rb +2 -3
- data/lib/rails/generators/actions.rb +4 -4
- data/lib/rails/generators/base.rb +1 -1
- data/lib/rails/generators/erb/scaffold/scaffold_generator.rb +1 -6
- data/lib/rails/generators/erb/scaffold/templates/_form.html.erb +4 -4
- data/lib/rails/generators/erb/scaffold/templates/edit.html.erb +3 -3
- data/lib/rails/generators/erb/scaffold/templates/index.html.erb +7 -7
- data/lib/rails/generators/erb/scaffold/templates/new.html.erb +2 -2
- data/lib/rails/generators/erb/scaffold/templates/show.html.erb +3 -3
- data/lib/rails/generators/generated_attribute.rb +2 -1
- data/lib/rails/generators/named_base.rb +24 -0
- data/lib/rails/generators/rails/app/app_generator.rb +10 -9
- data/lib/rails/generators/rails/app/templates/Gemfile +4 -3
- data/lib/rails/generators/rails/app/templates/README +6 -31
- data/lib/rails/generators/rails/app/templates/Rakefile +1 -1
- data/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb +0 -1
- data/lib/rails/generators/rails/app/templates/app/mailers/.empty_directory +0 -0
- data/lib/rails/generators/rails/app/templates/config/application.rb +11 -11
- data/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml +36 -24
- data/lib/rails/generators/rails/app/templates/config/databases/mysql.yml +1 -1
- data/lib/rails/generators/rails/app/templates/config/databases/oracle.yml +1 -1
- data/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt +3 -0
- data/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +3 -0
- data/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +3 -0
- data/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb +1 -1
- data/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt +2 -2
- data/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt +2 -2
- data/lib/rails/generators/rails/app/templates/config/routes.rb +1 -1
- data/lib/rails/generators/rails/app/templates/public/index.html +0 -17
- data/lib/rails/generators/rails/app/templates/public/javascripts/prototype.js +2027 -900
- data/lib/rails/generators/rails/app/templates/public/javascripts/rails.js +114 -57
- data/lib/rails/generators/rails/app/templates/test/test_helper.rb.tt +1 -1
- data/lib/rails/generators/rails/model/USAGE +1 -1
- data/lib/rails/generators/rails/resource/resource_generator.rb +4 -14
- data/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb +0 -2
- data/lib/rails/generators/rails/scaffold_controller/templates/controller.rb +28 -30
- data/lib/rails/generators/resource_helpers.rb +1 -1
- data/lib/rails/generators/test_case.rb +25 -11
- data/lib/rails/generators/test_unit/model/model_generator.rb +1 -1
- data/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +0 -1
- data/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +13 -15
- data/lib/rails/info.rb +1 -2
- data/lib/rails/info_routes.rb +1 -1
- data/lib/rails/initializable.rb +3 -16
- data/lib/rails/paths.rb +31 -36
- data/lib/rails/plugin.rb +10 -6
- data/lib/rails/rack/logger.rb +11 -13
- data/lib/rails/railtie.rb +14 -42
- data/lib/rails/ruby_version_check.rb +19 -5
- data/lib/rails/script_rails_loader.rb +29 -0
- data/lib/rails/tasks/annotations.rake +2 -2
- data/lib/rails/tasks/documentation.rake +47 -16
- data/lib/rails/tasks/framework.rake +9 -9
- data/lib/rails/tasks/middleware.rake +1 -1
- data/lib/rails/tasks/misc.rake +5 -5
- data/lib/rails/tasks/routes.rake +1 -1
- data/lib/rails/tasks/tmp.rake +5 -5
- data/lib/rails/test_unit/testing.rake +38 -14
- data/lib/rails/version.rb +1 -1
- metadata +29 -17
- data/README +0 -281
- data/lib/rails/application/routes_reloader.rb +0 -46
- data/lib/rails/log_subscriber.rb +0 -115
- data/lib/rails/log_subscriber/test_helper.rb +0 -97
- data/lib/rails/webrick_server.rb +0 -156
@@ -1,22 +1,22 @@
|
|
1
1
|
h2. Active Record Validations and Callbacks
|
2
2
|
|
3
|
-
This guide teaches you how to hook into the
|
3
|
+
This guide teaches you how to hook into the life cycle of your Active Record objects. You will learn how to validate the state of objects before they go into the database, and how to perform custom operations at certain points in the object life cycle.
|
4
4
|
|
5
5
|
After reading this guide and trying out the presented concepts, we hope that you'll be able to:
|
6
6
|
|
7
|
-
* Understand the
|
7
|
+
* Understand the life cycle of Active Record objects
|
8
8
|
* Use the built-in Active Record validation helpers
|
9
9
|
* Create your own custom validation methods
|
10
10
|
* Work with the error messages generated by the validation process
|
11
|
-
* Create callback methods that respond to events in the object
|
11
|
+
* Create callback methods that respond to events in the object life cycle
|
12
12
|
* Create special classes that encapsulate common behavior for your callbacks
|
13
|
-
* Create Observers that respond to
|
13
|
+
* Create Observers that respond to life cycle events outside of the original class
|
14
14
|
|
15
15
|
endprologue.
|
16
16
|
|
17
|
-
h3. The Object
|
17
|
+
h3. The Object Life Cycle
|
18
18
|
|
19
|
-
During the normal operation of a Rails application objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object
|
19
|
+
During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object life cycle</em> so that you can control your application and its data.
|
20
20
|
|
21
21
|
Validations allow you to ensure that only valid data is stored in your database. Callbacks and observers allow you to trigger logic before or after an alteration of an object's state.
|
22
22
|
|
@@ -57,7 +57,7 @@ We can see how it works by looking at some +rails console+ output:
|
|
57
57
|
=> false
|
58
58
|
</shell>
|
59
59
|
|
60
|
-
Creating and saving a new record will send
|
60
|
+
Creating and saving a new record will send a SQL +INSERT+ operation to the database. Updating an existing record will send a SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
|
61
61
|
|
62
62
|
CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.
|
63
63
|
|
@@ -71,7 +71,7 @@ The following methods trigger validations, and will save the object to the datab
|
|
71
71
|
* +update_attributes+
|
72
72
|
* +update_attributes!+
|
73
73
|
|
74
|
-
The bang versions (e.g. +save!+) raise an exception if the record is invalid. The non-bang versions don't: +save+ and +update_attributes+ return +false+, +create+ and +update+ just return the
|
74
|
+
The bang versions (e.g. +save!+) raise an exception if the record is invalid. The non-bang versions don't: +save+ and +update_attributes+ return +false+, +create+ and +update+ just return the objects.
|
75
75
|
|
76
76
|
h4. Skipping Validations
|
77
77
|
|
@@ -86,9 +86,9 @@ The following methods skip validations, and will save the object to the database
|
|
86
86
|
* +update_attribute+
|
87
87
|
* +update_counters+
|
88
88
|
|
89
|
-
Note that +save+ also has the ability to skip validations if passed
|
89
|
+
Note that +save+ also has the ability to skip validations if passed +:validate => false+ as argument. This technique should be used with caution.
|
90
90
|
|
91
|
-
* +save(false)+
|
91
|
+
* +save(:validate => false)+
|
92
92
|
|
93
93
|
h4. +valid?+ and +invalid?+
|
94
94
|
|
@@ -240,9 +240,9 @@ class Account < ActiveRecord::Base
|
|
240
240
|
end
|
241
241
|
</ruby>
|
242
242
|
|
243
|
-
The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+
|
243
|
+
The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. This example uses the +:message+ option to show how you can include the attribute's value.
|
244
244
|
|
245
|
-
The default error message for +validates_exclusion_of+
|
245
|
+
The default error message for +validates_exclusion_of+ is "_is reserved_".
|
246
246
|
|
247
247
|
h4. +validates_format_of+
|
248
248
|
|
@@ -270,7 +270,7 @@ end
|
|
270
270
|
|
271
271
|
The +validates_inclusion_of+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. The previous example uses the +:message+ option to show how you can include the attribute's value.
|
272
272
|
|
273
|
-
The default error message for +validates_inclusion_of+
|
273
|
+
The default error message for +validates_inclusion_of+ is "_is not included in the list_".
|
274
274
|
|
275
275
|
h4. +validates_length_of+
|
276
276
|
|
@@ -343,7 +343,7 @@ Besides +:only_integer+, the +validates_numericality_of+ helper also accepts the
|
|
343
343
|
* +:greater_than_or_equal_to+ - Specifies the value must be greater than or equal to the supplied value. The default error message for this option is "_must be greater than or equal to %{count}_".
|
344
344
|
* +:equal_to+ - Specifies the value must be equal to the supplied value. The default error message for this option is "_must be equal to %{count}_".
|
345
345
|
* +:less_than+ - Specifies the value must be less than the supplied value. The default error message for this option is "_must be less than %{count}_".
|
346
|
-
* +:less_than_or_equal_to+ - Specifies the value must be less than or equal the supplied value. The default error message for this option is "_must be less or equal to %{count}_".
|
346
|
+
* +:less_than_or_equal_to+ - Specifies the value must be less than or equal the supplied value. The default error message for this option is "_must be less than or equal to %{count}_".
|
347
347
|
* +:odd+ - Specifies the value must be an odd number if set to true. The default error message for this option is "_must be odd_".
|
348
348
|
* +:even+ - Specifies the value must be an even number if set to true. The default error message for this option is "_must be even_".
|
349
349
|
|
@@ -374,7 +374,7 @@ The default error message for +validates_presence_of+ is "_can't be empty_".
|
|
374
374
|
|
375
375
|
h4. +validates_uniqueness_of+
|
376
376
|
|
377
|
-
This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create
|
377
|
+
This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index in your database.
|
378
378
|
|
379
379
|
<ruby>
|
380
380
|
class Account < ActiveRecord::Base
|
@@ -423,14 +423,14 @@ class GoodnessValidator < ActiveRecord::Validator
|
|
423
423
|
end
|
424
424
|
</ruby>
|
425
425
|
|
426
|
-
The +validates_with+ helper takes a class, or a list of classes to use for validation.
|
426
|
+
The +validates_with+ helper takes a class, or a list of classes to use for validation. There is no default error message for +validates_with+. You must manually add errors to the record's errors collection in the validator class.
|
427
427
|
|
428
428
|
The validator class has two attributes by default:
|
429
429
|
|
430
430
|
* +record+ - the record to be validated
|
431
431
|
* +options+ - the extra options that were passed to +validates_with+
|
432
432
|
|
433
|
-
Like all other validations, +validates_with+ takes the +:if+, +:unless+ and +:on+ options.
|
433
|
+
Like all other validations, +validates_with+ takes the +:if+, +:unless+ and +:on+ options. If you pass any other options, it will send those options to the validator class as +options+:
|
434
434
|
|
435
435
|
<ruby>
|
436
436
|
class Person < ActiveRecord::Base
|
@@ -494,7 +494,7 @@ As you've already seen, the +:message+ option lets you specify the message that
|
|
494
494
|
|
495
495
|
h4. +:on+
|
496
496
|
|
497
|
-
The +:on+ option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be
|
497
|
+
The +:on+ option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be run on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +:on => :create+ to run the validation only when a new record is created or +:on => :update+ to run the validation only when a record is updated.
|
498
498
|
|
499
499
|
<ruby>
|
500
500
|
class Person < ActiveRecord::Base
|
@@ -573,7 +573,7 @@ class Invoice < ActiveRecord::Base
|
|
573
573
|
end
|
574
574
|
</ruby>
|
575
575
|
|
576
|
-
You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find useful to express that a certain field corresponds to a set of choices:
|
576
|
+
You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices:
|
577
577
|
|
578
578
|
<ruby>
|
579
579
|
ActiveRecord::Base.class_eval do
|
@@ -599,7 +599,7 @@ The following is a list of the most commonly used methods. Please refer to the +
|
|
599
599
|
|
600
600
|
h4(#working_with_validation_errors-errors). +errors+
|
601
601
|
|
602
|
-
Returns an OrderedHash with all errors. Each key is the attribute name and value is an array of strings with all errors.
|
602
|
+
Returns an OrderedHash with all errors. Each key is the attribute name and the value is an array of strings with all errors.
|
603
603
|
|
604
604
|
<ruby>
|
605
605
|
class Person < ActiveRecord::Base
|
@@ -619,7 +619,7 @@ person.errors # => []
|
|
619
619
|
|
620
620
|
h4(#working_with_validation_errors-errors-2). +errors[]+
|
621
621
|
|
622
|
-
+errors[]+ is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute returns an empty array.
|
622
|
+
+errors[]+ is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.
|
623
623
|
|
624
624
|
<ruby>
|
625
625
|
class Person < ActiveRecord::Base
|
@@ -681,7 +681,7 @@ Another way to do this is using +[]=+ setter
|
|
681
681
|
|
682
682
|
h4. +errors[:base]+
|
683
683
|
|
684
|
-
You can add
|
684
|
+
You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since +errors[:base]+ is an array, you can simply add a string to the array and uses it as the error message.
|
685
685
|
|
686
686
|
<ruby>
|
687
687
|
class Person < ActiveRecord::Base
|
@@ -789,7 +789,7 @@ Both the +form.error_messages+ and the +error_messages_for+ helpers accept optio
|
|
789
789
|
:header_tag => :h3 %>
|
790
790
|
</erb>
|
791
791
|
|
792
|
-
Which results in the following content
|
792
|
+
Which results in the following content:
|
793
793
|
|
794
794
|
!images/customized_error_messages.png(Customized error messages)!
|
795
795
|
|
@@ -799,7 +799,7 @@ h4. Customizing the Error Messages CSS
|
|
799
799
|
|
800
800
|
The selectors to customize the style of error messages are:
|
801
801
|
|
802
|
-
* +.
|
802
|
+
* +.field_with_errors+ - Style for the form fields and labels with errors.
|
803
803
|
* +#errorExplanation+ - Style for the +div+ element with the error messages.
|
804
804
|
* +#errorExplanation h2+ - Style for the header of the +div+ element.
|
805
805
|
* +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element.
|
@@ -811,7 +811,7 @@ The name of the class and the id can be changed with the +:class+ and +:id+ opti
|
|
811
811
|
|
812
812
|
h4. Customizing the Error Messages HTML
|
813
813
|
|
814
|
-
By default, form fields with errors are displayed enclosed by a +div+ element with the +
|
814
|
+
By default, form fields with errors are displayed enclosed by a +div+ element with the +field_with_errors+ CSS class. However, it's possible to override that.
|
815
815
|
|
816
816
|
The way form fields with errors are treated is defined by +ActionView::Base.field_error_proc+. This is a +Proc+ that receives two parameters:
|
817
817
|
|
@@ -838,7 +838,7 @@ This will result in something like the following:
|
|
838
838
|
|
839
839
|
h3. Callbacks Overview
|
840
840
|
|
841
|
-
Callbacks are methods that get called at certain moments of an object's
|
841
|
+
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
|
842
842
|
|
843
843
|
h4. Callback Registration
|
844
844
|
|
@@ -984,7 +984,7 @@ h3. Halting Execution
|
|
984
984
|
|
985
985
|
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
|
986
986
|
|
987
|
-
The whole callback chain is wrapped in a transaction. If any before callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued
|
987
|
+
The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception.
|
988
988
|
|
989
989
|
WARNING. Raising an arbitrary exception may break code that expects +save+ and friends not to fail like that. The +ActiveRecord::Rollback+ exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised.
|
990
990
|
|
@@ -1020,7 +1020,7 @@ Like in validations, we can also make our callbacks conditional, calling them on
|
|
1020
1020
|
|
1021
1021
|
h4. Using +:if+ and +:unless+ with a Symbol
|
1022
1022
|
|
1023
|
-
You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before the callback.
|
1023
|
+
You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before the callback. When using the +:if+ option, the callback won't be executed if the method returns false; when using the +:unless+ option, the callback won't be executed if the method returns true. This is the most common option. Using this form of registration it's also possible to register several different methods that should be called to check if the callback should be executed.
|
1024
1024
|
|
1025
1025
|
<ruby>
|
1026
1026
|
class Order < ActiveRecord::Base
|
@@ -1135,7 +1135,7 @@ Observers are conventionally placed inside of your +app/models+ directory and re
|
|
1135
1135
|
config.active_record.observers = :user_observer
|
1136
1136
|
</ruby>
|
1137
1137
|
|
1138
|
-
As usual, settings in +config/environments+ take precedence over those in +config/environment.rb+. So, if you prefer that an observer
|
1138
|
+
As usual, settings in +config/environments+ take precedence over those in +config/environment.rb+. So, if you prefer that an observer doesn't run in all environments, you can simply register it in a specific environment instead.
|
1139
1139
|
|
1140
1140
|
h4. Sharing Observers
|
1141
1141
|
|
@@ -1162,6 +1162,7 @@ h3. Changelog
|
|
1162
1162
|
|
1163
1163
|
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
|
1164
1164
|
|
1165
|
+
* July 20, 2010: Fixed typos and rephrased some paragraphs for clarity. "Jaime Iniesta":http://jaimeiniesta.com
|
1165
1166
|
* May 24, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
|
1166
1167
|
* May 15, 2010: Validation Errors section updated by "Emili Parreño":http://www.eparreno.com
|
1167
1168
|
* March 7, 2009: Callbacks revision by Trevor Turk
|
@@ -24,7 +24,7 @@ h5. Cherry-picking a Definition
|
|
24
24
|
|
25
25
|
The most lightweight way to get +blank?+ is to cherry-pick the file that defines it.
|
26
26
|
|
27
|
-
For every single method defined as a core extension this guide has a note that says where
|
27
|
+
For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of +blank?+ the note reads:
|
28
28
|
|
29
29
|
NOTE: Defined in +active_support/core_ext/object/blank.rb+.
|
30
30
|
|
@@ -124,7 +124,7 @@ NOTE: Defined in +active_support/core_ext/object/blank.rb+.
|
|
124
124
|
|
125
125
|
h4. +duplicable?+
|
126
126
|
|
127
|
-
A few fundamental objects in Ruby are singletons. For example, in the whole
|
127
|
+
A few fundamental objects in Ruby are singletons. For example, in the whole life of a program the integer 1 refers always to the same instance:
|
128
128
|
|
129
129
|
<ruby>
|
130
130
|
1.object_id # => 3
|
@@ -157,21 +157,6 @@ WARNING. Using +duplicable?+ is discouraged because it depends on a hard-coded l
|
|
157
157
|
|
158
158
|
NOTE: Defined in +active_support/core_ext/object/duplicable.rb+.
|
159
159
|
|
160
|
-
h4. +returning+
|
161
|
-
|
162
|
-
The method +returning+ yields its argument to a block and returns it. You tipically use it with a mutable object that gets modified in the block:
|
163
|
-
|
164
|
-
<ruby>
|
165
|
-
def html_options_for_form(url_for_options, options, *parameters_for_url)
|
166
|
-
returning options.stringify_keys do |html_options|
|
167
|
-
html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
|
168
|
-
html_options["action"] = url_for(url_for_options, *parameters_for_url)
|
169
|
-
end
|
170
|
-
end
|
171
|
-
</ruby>
|
172
|
-
|
173
|
-
NOTE: Defined in +active_support/core_ext/object/returning.rb+.
|
174
|
-
|
175
160
|
h4. +try+
|
176
161
|
|
177
162
|
Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first.
|
@@ -187,7 +172,7 @@ def log_info(sql, name, ms)
|
|
187
172
|
end
|
188
173
|
</ruby>
|
189
174
|
|
190
|
-
You can shorten that using +Object#try+. This method is a
|
175
|
+
You can shorten that using +Object#try+. This method is a synonym for +Object#send+ except that it returns +nil+ if sent to +nil+. The previous example could then be rewritten as:
|
191
176
|
|
192
177
|
<ruby>
|
193
178
|
def log_info(sql, name, ms)
|
@@ -209,8 +194,7 @@ String.singleton_class # => #<Class:String>
|
|
209
194
|
String.new.singleton_class # => #<Class:#<String:0x17a1d1c>>
|
210
195
|
</ruby>
|
211
196
|
|
212
|
-
WARNING: Fixnums and symbols have no singleton classes, +singleton_class+
|
213
|
-
raises +TypeError+ on them. Moreover, the singleton classes of +nil+, +true+, and +false+, are +NilClass+, +TrueClass+, and +FalseClass+, respectively.
|
197
|
+
WARNING: Fixnums and symbols have no singleton classes, +singleton_class+ raises +TypeError+ on them. Moreover, the singleton classes of +nil+, +true+, and +false+, are +NilClass+, +TrueClass+, and +FalseClass+, respectively.
|
214
198
|
|
215
199
|
NOTE: Defined in +active_support/core_ext/kernel/singleton_class.rb+.
|
216
200
|
|
@@ -256,7 +240,7 @@ NOTE: Defined in +active_support/core_ext/object/acts_like.rb+.
|
|
256
240
|
|
257
241
|
h4. +to_param+
|
258
242
|
|
259
|
-
All objects in Rails respond to the method +to_param+, which is meant to return something that represents them as values in a query string, or as
|
243
|
+
All objects in Rails respond to the method +to_param+, which is meant to return something that represents them as values in a query string, or as URL fragments.
|
260
244
|
|
261
245
|
By default +to_param+ just calls +to_s+:
|
262
246
|
|
@@ -294,7 +278,7 @@ we get:
|
|
294
278
|
user_path(@user) # => "/users/357-john-smith"
|
295
279
|
</ruby>
|
296
280
|
|
297
|
-
WARNING. Controllers need to be aware of any
|
281
|
+
WARNING. Controllers need to be aware of any redefinition of +to_param+ because when a request like that comes in "357-john-smith" is the value of +params[:id]+.
|
298
282
|
|
299
283
|
NOTE: Defined in +active_support/core_ext/object/to_param.rb+.
|
300
284
|
|
@@ -332,7 +316,7 @@ Arrays return the result of applying +to_query+ to each element with <tt>_key_[]
|
|
332
316
|
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
|
333
317
|
</ruby>
|
334
318
|
|
335
|
-
Hashes also respond to +to_query+ but with a different signature. If no argument is passed a call generates a sorted series of key/value
|
319
|
+
Hashes also respond to +to_query+ but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling +to_query(key)+ on its values. Then it joins the result with "&":
|
336
320
|
|
337
321
|
<ruby>
|
338
322
|
{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3"
|
@@ -388,40 +372,6 @@ TIP: Since +with_options+ forwards calls to its receiver they can be nested. Eac
|
|
388
372
|
|
389
373
|
NOTE: Defined in +active_support/core_ext/object/with_options.rb+.
|
390
374
|
|
391
|
-
h5. +subclasses_of+
|
392
|
-
|
393
|
-
The method +subclasses_of+ receives an arbitrary number of class objects and returns all their anonymous or reachable descendants as a single array:
|
394
|
-
|
395
|
-
<ruby>
|
396
|
-
class C; end
|
397
|
-
subclasses_of(C) # => []
|
398
|
-
|
399
|
-
subclasses_of(Integer) # => [Bignum, Fixnum]
|
400
|
-
|
401
|
-
module M
|
402
|
-
class A; end
|
403
|
-
class B1 < A; end
|
404
|
-
class B2 < A; end
|
405
|
-
end
|
406
|
-
|
407
|
-
module N
|
408
|
-
class C < M::B1; end
|
409
|
-
end
|
410
|
-
|
411
|
-
subclasses_of(M::A) # => [N::C, M::B2, M::B1]
|
412
|
-
</ruby>
|
413
|
-
|
414
|
-
The order in which these classes are returned is unspecified. The returned collection may have duplicates:
|
415
|
-
|
416
|
-
<ruby>
|
417
|
-
subclasses_of(Numeric, Integer)
|
418
|
-
# => [Bignum, Float, Fixnum, Integer, Date::Infinity, Rational, BigDecimal, Bignum, Fixnum]
|
419
|
-
</ruby>
|
420
|
-
|
421
|
-
See also +Class#subclasses+ in "Extensions to +Class+ FIX THIS LINK":FIXME.
|
422
|
-
|
423
|
-
NOTE: Defined in +active_support/core_ext/object/extending.rb+.
|
424
|
-
|
425
375
|
h4. Instance Variables
|
426
376
|
|
427
377
|
Active Support provides several methods to ease access to instance variables.
|
@@ -656,9 +606,9 @@ h5. Internal Attributes
|
|
656
606
|
|
657
607
|
When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries.
|
658
608
|
|
659
|
-
Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the
|
609
|
+
Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
|
660
610
|
|
661
|
-
The macro +attr_internal+ is a
|
611
|
+
The macro +attr_internal+ is a synonym for +attr_internal_accessor+:
|
662
612
|
|
663
613
|
<ruby>
|
664
614
|
# library
|
@@ -721,7 +671,7 @@ h4. Method Delegation
|
|
721
671
|
|
722
672
|
The class method +delegate+ offers an easy way to forward methods.
|
723
673
|
|
724
|
-
For example, if +User+ has some details like the age factored out to +Profile+, it could be handy to still be able to
|
674
|
+
For example, if +User+ has some details like the age factored out to +Profile+, it could be handy to still be able to access such attributes directly, <tt>user.age</tt>, instead of having to explicit the chain <tt>user.profile.age</tt>.
|
725
675
|
|
726
676
|
That can be accomplished by hand:
|
727
677
|
|
@@ -816,6 +766,28 @@ end
|
|
816
766
|
|
817
767
|
This may come in handy if you need to define a method that may already exist, since redefining a method issues a warning "method redefined; discarding old redefined_method_name".
|
818
768
|
|
769
|
+
h5. +redefine_method(method_name, &block)+
|
770
|
+
|
771
|
+
The method first removes method with given name (using +remove_possible_method+) and then defines new one.
|
772
|
+
|
773
|
+
<ruby>
|
774
|
+
class A; end
|
775
|
+
|
776
|
+
A.class_eval do
|
777
|
+
redefine_method(:foobar) do |foo|
|
778
|
+
#do something here
|
779
|
+
end
|
780
|
+
|
781
|
+
#Code above does the same as this:
|
782
|
+
|
783
|
+
method_name = :foobar
|
784
|
+
remove_possible_method(method_name)
|
785
|
+
define_method(method_name) do |foo|
|
786
|
+
#do something here
|
787
|
+
end
|
788
|
+
end
|
789
|
+
</ruby>
|
790
|
+
|
819
791
|
NOTE: Defined in +active_support/core_ext/module/remove_method.rb+.
|
820
792
|
|
821
793
|
h4. Parents
|
@@ -935,7 +907,7 @@ NOTE: Defined in +active_support/core_ext/module/synchronization.rb+.
|
|
935
907
|
|
936
908
|
h4. Reachable
|
937
909
|
|
938
|
-
A named module is reachable if it is stored in its
|
910
|
+
A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant.
|
939
911
|
|
940
912
|
That is what ordinarily happens, if a module is called "M", the +M+ constant exists and holds it:
|
941
913
|
|
@@ -1016,7 +988,9 @@ h3. Extensions to +Class+
|
|
1016
988
|
|
1017
989
|
h4. Class Attributes
|
1018
990
|
|
1019
|
-
|
991
|
+
h5. +class_attribute+
|
992
|
+
|
993
|
+
The method +class_attribute+ declares one or more inheritable class attributes that can be overridden at any level down the hierarchy:
|
1020
994
|
|
1021
995
|
<ruby>
|
1022
996
|
class A
|
@@ -1040,17 +1014,50 @@ A.x # => :a
|
|
1040
1014
|
B.x # => :b
|
1041
1015
|
</ruby>
|
1042
1016
|
|
1043
|
-
For example
|
1017
|
+
For example +ActionMailer::Base+ defines:
|
1044
1018
|
|
1045
1019
|
<ruby>
|
1046
|
-
class_attribute :
|
1047
|
-
self.
|
1020
|
+
class_attribute :default_params
|
1021
|
+
self.default_params = {
|
1022
|
+
:mime_version => "1.0",
|
1023
|
+
:charset => "UTF-8",
|
1024
|
+
:content_type => "text/plain",
|
1025
|
+
:parts_order => [ "text/plain", "text/enriched", "text/html" ]
|
1026
|
+
}.freeze
|
1048
1027
|
</ruby>
|
1049
1028
|
|
1050
|
-
|
1029
|
+
They can be also accessed and overridden at the instance level:
|
1030
|
+
|
1031
|
+
<ruby>
|
1032
|
+
A.x = 1
|
1033
|
+
|
1034
|
+
a1 = A.new
|
1035
|
+
a2 = A.new
|
1036
|
+
a2.x = 2
|
1037
|
+
|
1038
|
+
a1.x # => 1, comes from A
|
1039
|
+
a2.x # => 2, overridden in a2
|
1040
|
+
</ruby>
|
1041
|
+
|
1042
|
+
The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to false, as in
|
1043
|
+
|
1044
|
+
<ruby>
|
1045
|
+
module AcitveRecord
|
1046
|
+
class Base
|
1047
|
+
class_attribute :table_name_prefix, :instance_writer => false
|
1048
|
+
self.table_name_prefix = ""
|
1049
|
+
end
|
1050
|
+
end
|
1051
|
+
</ruby>
|
1052
|
+
|
1053
|
+
A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
|
1054
|
+
|
1055
|
+
For convenience +class_attribute+ defines also an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
|
1051
1056
|
|
1052
1057
|
NOTE: Defined in +active_support/core_ext/class/attribute.rb+
|
1053
1058
|
|
1059
|
+
h5. +cattr_reader+, +cattr_writer+, and +cattr_accessor+
|
1060
|
+
|
1054
1061
|
The macros +cattr_reader+, +cattr_writer+, and +cattr_accessor+ are analogous to their +attr_*+ counterparts but for classes. They initialize a class variable to +nil+ unless it already exists, and generate the corresponding class methods to access it:
|
1055
1062
|
|
1056
1063
|
<ruby>
|
@@ -1061,17 +1068,18 @@ class MysqlAdapter < AbstractAdapter
|
|
1061
1068
|
end
|
1062
1069
|
</ruby>
|
1063
1070
|
|
1064
|
-
Instance methods are created as well for convenience. For example given
|
1071
|
+
Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with +class_attribute+ (see above). For example given
|
1065
1072
|
|
1066
1073
|
<ruby>
|
1067
|
-
module
|
1074
|
+
module ActionView
|
1068
1075
|
class Base
|
1069
|
-
cattr_accessor :
|
1076
|
+
cattr_accessor :field_error_proc
|
1077
|
+
@@field_error_proc = Proc.new{ ... }
|
1070
1078
|
end
|
1071
1079
|
end
|
1072
1080
|
</ruby>
|
1073
1081
|
|
1074
|
-
we can access +
|
1082
|
+
we can access +field_error_proc+ in views. The generation of the writer instance method can be prevented by setting +:instance_writer+ to +false+ (not any false value, but exactly +false+):
|
1075
1083
|
|
1076
1084
|
<ruby>
|
1077
1085
|
module ActiveRecord
|
@@ -1082,13 +1090,13 @@ module ActiveRecord
|
|
1082
1090
|
end
|
1083
1091
|
</ruby>
|
1084
1092
|
|
1085
|
-
A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
|
1093
|
+
A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
|
1086
1094
|
|
1087
1095
|
NOTE: Defined in +active_support/core_ext/class/attribute_accessors.rb+.
|
1088
1096
|
|
1089
1097
|
h4. Class Inheritable Attributes
|
1090
1098
|
|
1091
|
-
Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros +class_inheritable_reader+, +class_inheritable_writer+, and +class_inheritable_accessor+ provide
|
1099
|
+
Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros +class_inheritable_reader+, +class_inheritable_writer+, and +class_inheritable_accessor+ provide accessors for class-level data which is inherited but not shared with children:
|
1092
1100
|
|
1093
1101
|
<ruby>
|
1094
1102
|
module ActionController
|
@@ -1142,36 +1150,51 @@ If for whatever reason an application loads the definition of a mailer class and
|
|
1142
1150
|
|
1143
1151
|
NOTE: Defined in +active_support/core_ext/class/delegating_attributes.rb+.
|
1144
1152
|
|
1145
|
-
h4. Descendants
|
1153
|
+
h4. Subclasses & Descendants
|
1146
1154
|
|
1147
1155
|
h5. +subclasses+
|
1148
1156
|
|
1149
|
-
The +subclasses+ method returns the
|
1157
|
+
The +subclasses+ method returns the subclasses of the receiver:
|
1150
1158
|
|
1151
1159
|
<ruby>
|
1152
1160
|
class C; end
|
1153
1161
|
C.subclasses # => []
|
1154
1162
|
|
1155
|
-
|
1156
|
-
|
1157
|
-
module M
|
1158
|
-
class A; end
|
1159
|
-
class B1 < A; end
|
1160
|
-
class B2 < A; end
|
1161
|
-
end
|
1163
|
+
class B < C; end
|
1164
|
+
C.subclasses # => [B]
|
1162
1165
|
|
1163
|
-
|
1164
|
-
|
1165
|
-
end
|
1166
|
+
class A < B; end
|
1167
|
+
C.subclasses # => [B]
|
1166
1168
|
|
1167
|
-
|
1169
|
+
class D < C; end
|
1170
|
+
C.subclasses # => [B, D]
|
1168
1171
|
</ruby>
|
1169
1172
|
|
1170
|
-
The order in which these
|
1173
|
+
The order in which these classes are returned is unspecified.
|
1174
|
+
|
1175
|
+
WARNING: This method is redefined in some Rails core classes but should be all compatible in Rails 3.1.
|
1176
|
+
|
1177
|
+
NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.
|
1178
|
+
|
1179
|
+
h5. +descendants+
|
1180
|
+
|
1181
|
+
The +descendants+ method returns all classes that are <tt><</tt> than its receiver:
|
1182
|
+
|
1183
|
+
<ruby>
|
1184
|
+
class C; end
|
1185
|
+
C.descendants # => []
|
1186
|
+
|
1187
|
+
class B < C; end
|
1188
|
+
C.descendants # => [B]
|
1171
1189
|
|
1172
|
-
|
1190
|
+
class A < B; end
|
1191
|
+
C.descendants # => [B, A]
|
1192
|
+
|
1193
|
+
class D < C; end
|
1194
|
+
C.descendants # => [B, A, D]
|
1195
|
+
</ruby>
|
1173
1196
|
|
1174
|
-
|
1197
|
+
The order in which these classes are returned is unspecified.
|
1175
1198
|
|
1176
1199
|
NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.
|
1177
1200
|
|
@@ -1204,7 +1227,7 @@ s.html_safe? # => true
|
|
1204
1227
|
s # => "<script>...</script>"
|
1205
1228
|
</ruby>
|
1206
1229
|
|
1207
|
-
It is your
|
1230
|
+
It is your responsibility to ensure calling +html_safe+ on a particular string is fine.
|
1208
1231
|
|
1209
1232
|
NOTE: For performance reasons safe strings are implemented in a way that cannot offer an in-place +html_safe!+ variant.
|
1210
1233
|
|
@@ -1377,7 +1400,7 @@ The method +pluralize+ returns the plural of its receiver:
|
|
1377
1400
|
"equipment".pluralize # => "equipment"
|
1378
1401
|
</ruby>
|
1379
1402
|
|
1380
|
-
As the previous example shows, Active Support knows some irregular plurals and uncountable nouns.
|
1403
|
+
As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in +config/initializers/inflections.rb+. That file is generated by the +rails+ command and has instructions in comments.
|
1381
1404
|
|
1382
1405
|
Active Record uses this method to compute the default table name that corresponds to a model:
|
1383
1406
|
|
@@ -1453,13 +1476,15 @@ end
|
|
1453
1476
|
|
1454
1477
|
That may be handy to compute method names in a language that follows that convention, for example JavaScript.
|
1455
1478
|
|
1479
|
+
INFO: As a rule of thumb you can think of +camelize+ as the inverse of +underscore+, though there are cases where that does not hold: <tt>"SSLError".underscore.camelize</tt> gives back <tt>"SslError"</tt>.
|
1480
|
+
|
1456
1481
|
+camelize+ is aliased to +camelcase+.
|
1457
1482
|
|
1458
1483
|
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
|
1459
1484
|
|
1460
1485
|
h5. +underscore+
|
1461
1486
|
|
1462
|
-
The method +underscore+
|
1487
|
+
The method +underscore+ goes the other way around, from camel case to paths:
|
1463
1488
|
|
1464
1489
|
<ruby>
|
1465
1490
|
"Product".underscore # => "product"
|
@@ -1492,6 +1517,8 @@ def load_missing_constant(from_mod, const_name)
|
|
1492
1517
|
end
|
1493
1518
|
</ruby>
|
1494
1519
|
|
1520
|
+
INFO: As a rule of thumb you can think of +underscore+ as the inverse of +camelize+, though there are cases where that does not hold. For example, <tt>"SSLError".underscore.camelize</tt> gives back <tt>"SslError"</tt>.
|
1521
|
+
|
1495
1522
|
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
|
1496
1523
|
|
1497
1524
|
h5. +titleize+
|
@@ -1697,6 +1724,90 @@ foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
|
|
1697
1724
|
|
1698
1725
|
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
|
1699
1726
|
|
1727
|
+
h4. Conversions
|
1728
|
+
|
1729
|
+
h5. +constantize+
|
1730
|
+
|
1731
|
+
The method +constantize+ expects the receiver to contain the name of a constant, and tries to get you the object stored in there, assuming it is defined:
|
1732
|
+
|
1733
|
+
<ruby>
|
1734
|
+
"ActiveRecord::Base".constantize # => ActiveRecord::Base
|
1735
|
+
</ruby>
|
1736
|
+
|
1737
|
+
The name is assumed to be top-level, no matter whether it starts with "::" or not. No lexical context is taken into account:
|
1738
|
+
|
1739
|
+
<ruby>
|
1740
|
+
C = 1
|
1741
|
+
module M
|
1742
|
+
C = 2
|
1743
|
+
"C".constantize # => 1, same as "::C".constantize
|
1744
|
+
end
|
1745
|
+
</ruby>
|
1746
|
+
|
1747
|
+
NOTE: Defined in +active_support/core_ext/string/conversions.rb+.
|
1748
|
+
|
1749
|
+
h5. +ord+
|
1750
|
+
|
1751
|
+
Ruby 1.9 defines +ord+ to be the codepoint of the first character of the receiver. Active Support backports +ord+ for single-byte encondings like ASCII or ISO-8859-1 in Ruby 1.8:
|
1752
|
+
|
1753
|
+
<ruby>
|
1754
|
+
"a".ord # => 97
|
1755
|
+
"à".ord # => 224, in ISO-8859-1
|
1756
|
+
</ruby>
|
1757
|
+
|
1758
|
+
In Ruby 1.8 +ord+ doesn't work in general in UTF8 strings, use the multibyte support in Active Support for that:
|
1759
|
+
|
1760
|
+
<ruby>
|
1761
|
+
"a".mb_chars.ord # => 97
|
1762
|
+
"à".mb_chars.ord # => 224, in UTF8
|
1763
|
+
</ruby>
|
1764
|
+
|
1765
|
+
Note that the 224 is different in both examples. In ISO-8859-1 "à" is represented as a single byte, 224. Its single-character representattion in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call +ord+ on the UTF8 string "à" the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus.
|
1766
|
+
|
1767
|
+
INFO: +ord+ is equivalent to +getbyte(0)+.
|
1768
|
+
|
1769
|
+
NOTE: Defined in +active_support/core_ext/string/conversions.rb+.
|
1770
|
+
|
1771
|
+
h5. +getbyte+
|
1772
|
+
|
1773
|
+
Active Support backports +getbyte+ from Ruby 1.9:
|
1774
|
+
|
1775
|
+
<ruby>
|
1776
|
+
"foo".getbyte(0) # => 102, same as "foo".ord
|
1777
|
+
"foo".getbyte(1) # => 111
|
1778
|
+
"foo".getbyte(9) # => nil
|
1779
|
+
"foo".getbyte(-1) # => 111
|
1780
|
+
</ruby>
|
1781
|
+
|
1782
|
+
INFO: +getbyte+ is equivalent to +[]+.
|
1783
|
+
|
1784
|
+
NOTE: Defined in +active_support/core_ext/string/conversions.rb+.
|
1785
|
+
|
1786
|
+
h5. +to_date+, +to_time+, +to_datetime+
|
1787
|
+
|
1788
|
+
The methods +to_date+, +to_time+, and +to_datetime+ are basically convenience wrappers around +Date._parse+:
|
1789
|
+
|
1790
|
+
<ruby>
|
1791
|
+
"2010-07-27".to_date # => Tue, 27 Jul 2010
|
1792
|
+
"2010-07-27 23:37:00".to_time # => Tue Jul 27 23:37:00 UTC 2010
|
1793
|
+
"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
|
1794
|
+
</ruby>
|
1795
|
+
|
1796
|
+
+to_time+ receives an optional argument +:utc+ or +:local+, to indicate which time zone you want the time in:
|
1797
|
+
|
1798
|
+
<ruby>
|
1799
|
+
"2010-07-27 23:42:00".to_time(:utc) # => Tue Jul 27 23:42:00 UTC 2010
|
1800
|
+
"2010-07-27 23:42:00".to_time(:local) # => Tue Jul 27 23:42:00 +0200 2010
|
1801
|
+
</ruby>
|
1802
|
+
|
1803
|
+
Default is +:utc+.
|
1804
|
+
|
1805
|
+
Please refer to the documentation of +Date._parse+ for further details.
|
1806
|
+
|
1807
|
+
INFO: The three of them return +nil+ for blank receivers.
|
1808
|
+
|
1809
|
+
NOTE: Defined in +active_support/core_ext/string/conversions.rb+.
|
1810
|
+
|
1700
1811
|
h3. Extensions to +Numeric+
|
1701
1812
|
|
1702
1813
|
h4. Bytes
|
@@ -1760,7 +1871,7 @@ h3. Extensions to +Float+
|
|
1760
1871
|
|
1761
1872
|
h4. +round+
|
1762
1873
|
|
1763
|
-
The
|
1874
|
+
The built-in method +Float#round+ rounds a float to the nearest integer. Active Support adds an optional parameter to let you specify a precision:
|
1764
1875
|
|
1765
1876
|
<ruby>
|
1766
1877
|
Math::E.round(4) # => 2.7183
|
@@ -1776,9 +1887,7 @@ h3. Extensions to +Enumerable+
|
|
1776
1887
|
|
1777
1888
|
h4. +group_by+
|
1778
1889
|
|
1779
|
-
Ruby 1.8.7
|
1780
|
-
|
1781
|
-
This iterator takes a block and builds an ordered hash with its return values as keys. Each key is mapped to the array of elements for which the block returned that value:
|
1890
|
+
Active Support redefines +group_by+ in Ruby 1.8.7 so that it returns an ordered hash as in 1.9:
|
1782
1891
|
|
1783
1892
|
<ruby>
|
1784
1893
|
entries_by_surname_initial = address_book.group_by do |entry|
|
@@ -1786,7 +1895,7 @@ entries_by_surname_initial = address_book.group_by do |entry|
|
|
1786
1895
|
end
|
1787
1896
|
</ruby>
|
1788
1897
|
|
1789
|
-
|
1898
|
+
Distinct block return values are added to the hash as they come, so that's the resulting order.
|
1790
1899
|
|
1791
1900
|
NOTE: Defined in +active_support/core_ext/enumerable.rb+.
|
1792
1901
|
|
@@ -1925,7 +2034,7 @@ Similarly, +from+ returns the tail from the element at the passed index on:
|
|
1925
2034
|
[].from(0) # => []
|
1926
2035
|
</ruby>
|
1927
2036
|
|
1928
|
-
The methods +second+, +third+, +fourth+, and +fifth+ return the corresponding element (+first+ is
|
2037
|
+
The methods +second+, +third+, +fourth+, and +fifth+ return the corresponding element (+first+ is built-in). Thanks to social wisdom and positive constructiveness all around, +forty_two+ is also available.
|
1929
2038
|
|
1930
2039
|
NOTE: Defined in +active_support/core_ext/array/access.rb+.
|
1931
2040
|
|
@@ -2120,7 +2229,7 @@ NOTE: Defined in +active_support/core_ext/array/conversions.rb+.
|
|
2120
2229
|
|
2121
2230
|
h4. Wrapping
|
2122
2231
|
|
2123
|
-
The class method +Array.wrap+ behaves like the function +Array()+ except that it does not try to call +to_a+ on its argument. That changes the
|
2232
|
+
The class method +Array.wrap+ behaves like the function +Array()+ except that it does not try to call +to_a+ on its argument. That changes the behavior for enumerables:
|
2124
2233
|
|
2125
2234
|
<ruby>
|
2126
2235
|
Array.wrap(:foo => :bar) # => [{:foo => :bar}]
|
@@ -2282,7 +2391,7 @@ NOTE: Defined in +active_support/core_ext/hash/conversions.rb+.
|
|
2282
2391
|
|
2283
2392
|
h4. Merging
|
2284
2393
|
|
2285
|
-
Ruby has a
|
2394
|
+
Ruby has a built-in method +Hash#merge+ that merges two hashes:
|
2286
2395
|
|
2287
2396
|
<ruby>
|
2288
2397
|
{:a => 1, :b => 1}.merge(:a => 0, :c => 2)
|
@@ -2511,7 +2620,7 @@ NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
|
|
2511
2620
|
|
2512
2621
|
h4. Slicing
|
2513
2622
|
|
2514
|
-
Ruby has
|
2623
|
+
Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:
|
2515
2624
|
|
2516
2625
|
<ruby>
|
2517
2626
|
{:a => 1, :b => 2, :c => 3}.slice(:a, :c)
|
@@ -2625,7 +2734,7 @@ Active Support extends this method so that the argument may be another range in
|
|
2625
2734
|
(1...9).include?(3..9) # => false
|
2626
2735
|
</ruby>
|
2627
2736
|
|
2628
|
-
WARNING: The
|
2737
|
+
WARNING: The original +Range#include?+ is still the one aliased to +Range#===+.
|
2629
2738
|
|
2630
2739
|
NOTE: Defined in +active_support/core_ext/range/include_range.rb+.
|
2631
2740
|
|
@@ -2885,11 +2994,9 @@ Date.new(2010, 1, 31).change(:month => 2)
|
|
2885
2994
|
# => ArgumentError: invalid date
|
2886
2995
|
</ruby>
|
2887
2996
|
|
2888
|
-
h5.
|
2889
|
-
|
2890
|
-
WARNING: The following methods do not take into account the user time zone. They return timestamps in localtime.
|
2997
|
+
h5. Timestamps
|
2891
2998
|
|
2892
|
-
INFO: The following methods return a +Time+ object if possible, otherwise a +DateTime+.
|
2999
|
+
INFO: The following methods return a +Time+ object if possible, otherwise a +DateTime+. If set, they honor the user time zone.
|
2893
3000
|
|
2894
3001
|
h6. +beginning_of_day+, +end_of_day+
|
2895
3002
|
|
@@ -2907,7 +3014,25 @@ date = Date.new(2010, 6, 7)
|
|
2907
3014
|
date.end_of_day # => Sun Jun 06 23:59:59 +0200 2010
|
2908
3015
|
</ruby>
|
2909
3016
|
|
2910
|
-
+beginning_of_day+ is aliased to +at_beginning_of_day+, +midnight+, +at_midnight
|
3017
|
+
+beginning_of_day+ is aliased to +at_beginning_of_day+, +midnight+, +at_midnight+.
|
3018
|
+
|
3019
|
+
h6. +ago+, +since+
|
3020
|
+
|
3021
|
+
The method +ago+ receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:
|
3022
|
+
|
3023
|
+
<ruby>
|
3024
|
+
date = Date.current # => Fri, 11 Jun 2010
|
3025
|
+
date.ago(1) # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
|
3026
|
+
</ruby>
|
3027
|
+
|
3028
|
+
Similarly, +since+ moves forward:
|
3029
|
+
|
3030
|
+
<ruby>
|
3031
|
+
date = Date.current # => Fri, 11 Jun 2010
|
3032
|
+
date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
|
3033
|
+
</ruby>
|
3034
|
+
|
3035
|
+
h5. Other Time Computations
|
2911
3036
|
|
2912
3037
|
h4(#date-conversions). Conversions
|
2913
3038
|
|
@@ -3064,7 +3189,7 @@ Active Support adds +missing_name?+ to +NameError+, which tests whether the exce
|
|
3064
3189
|
|
3065
3190
|
The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully-qualified constant name.
|
3066
3191
|
|
3067
|
-
TIP: A symbol can represent a fully-qualified constant name as in +:"ActiveRecord::Base"+, so the
|
3192
|
+
TIP: A symbol can represent a fully-qualified constant name as in +:"ActiveRecord::Base"+, so the behavior for symbols is defined for convenience, not because it has to be that way technically.
|
3068
3193
|
|
3069
3194
|
For example, when an action of +PostsController+ is called Rails tries optimistically to use +PostsHelper+. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that +posts_helper.rb+ raises a +NameError+ due to an actual unknown constant. That should be reraised. The method +missing_name?+ provides a way to distinguish both cases:
|
3070
3195
|
|