aboutsummaryrefslogtreecommitdiffstats
path: root/guides
diff options
context:
space:
mode:
Diffstat (limited to 'guides')
-rw-r--r--guides/source/4_2_release_notes.md4
-rw-r--r--guides/source/active_model_basics.md369
-rw-r--r--guides/source/active_record_validations.md10
-rw-r--r--guides/source/configuring.md30
-rw-r--r--guides/source/documents.yaml5
-rw-r--r--guides/source/testing.md1
6 files changed, 381 insertions, 38 deletions
diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md
index 2b8a6eb622..a598c7c319 100644
--- a/guides/source/4_2_release_notes.md
+++ b/guides/source/4_2_release_notes.md
@@ -79,7 +79,7 @@ post.comments(true) # uses cached pattern
The caching is not used in the following scenarios:
- The model has a default scope
-- The model uses single table inheritence to inherit from another model
+- The model uses single table inheritance to inherit from another model
- `find` with a list of ids. eg:
```ruby
@@ -753,7 +753,7 @@ Please refer to the [Changelog][active-support] for detailed changes.
* Introduced new configuration option `active_support.test_order` for
specifying the order test cases are executed. This option currently defaults
to `:sorted` but will be changed to `:random` in Rails 5.0.
- ([Commit](TODO: fill me in))
+ ([Commit](https://github.com/rails/rails/commit/53e877f7d9291b2bf0b8c425f9e32ef35829f35b))
* The `travel_to` test helper now truncates the `usec` component to 0.
([Commit](https://github.com/rails/rails/commit/9f6e82ee4783e491c20f5244a613fdeb4024beb5))
diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md
index 3eaeeff389..a520b91a4d 100644
--- a/guides/source/active_model_basics.md
+++ b/guides/source/active_model_basics.md
@@ -1,20 +1,32 @@
Active Model Basics
===================
-This guide should provide you with all you need to get started using model classes. Active Model allows for Action Pack helpers to interact with non-Active Record models. Active Model also helps building custom ORMs for use outside of the Rails framework.
+This guide should provide you with all you need to get started using model
+classes. Active Model allows for Action Pack helpers to interact with
+plain Ruby objects. Active Model also helps build custom ORMs for use
+outside of the Rails framework.
-After reading this guide, you will know:
+After reading this guide, you will be able to add to plain Ruby objects:
+
+* The ability to behave like an Active Record model.
+* Callbacks and validations like Active Record.
+* Serializers.
+* Integration with the Rails internationalization (i18n) framework.
--------------------------------------------------------------------------------
Introduction
------------
-Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below.
+Active Model is a library containing various modules used in developing
+classes that need some features present on Active Record.
+Some of these modules are explained below.
-### AttributeMethods
+### Attribute Methods
-The AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes and which methods on the object will use them.
+The `ActiveModel::AttributeMethods` module can add custom prefixes and suffixes
+on methods of a class. It is used by defining the prefixes and suffixes and
+which methods on the object will use them.
```ruby
class Person
@@ -38,14 +50,17 @@ end
person = Person.new
person.age = 110
-person.age_highest? # true
-person.reset_age # 0
-person.age_highest? # false
+person.age_highest? # => true
+person.reset_age # => 0
+person.age_highest? # => false
```
### Callbacks
-Callbacks gives Active Record style callbacks. This provides an ability to define callbacks which run at appropriate times. After defining callbacks, you can wrap them with before, after and around custom methods.
+`ActiveModel::Callbacks` gives Active Record style callbacks. This provides an
+ability to define callbacks which run at appropriate times.
+After defining callbacks, you can wrap them with before, after and around
+custom methods.
```ruby
class Person
@@ -69,7 +84,9 @@ end
### Conversion
-If a class defines `persisted?` and `id` methods, then you can include the `Conversion` module in that class and call the Rails conversion methods on objects of that class.
+If a class defines `persisted?` and `id` methods, then you can include the
+`ActiveModel::Conversion` module in that class and call the Rails conversion
+methods on objects of that class.
```ruby
class Person
@@ -92,11 +109,13 @@ person.to_param # => nil
### Dirty
-An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Let's consider a Person class with attributes `first_name` and `last_name`:
+An object becomes dirty when it has gone through one or more changes to its
+attributes and has not been saved. `ActiveModel::Dirty` gives the ability to
+check whether an object has been changed or not. It also has attribute based
+accessor methods. Let's consider a Person class with attributes `first_name`
+and `last_name`:
```ruby
-require 'active_model'
-
class Person
include ActiveModel::Dirty
define_attribute_methods :first_name, :last_name
@@ -162,10 +181,11 @@ Track what was the previous value of the attribute.
```ruby
# attr_name_was accessor
-person.first_name_was # => "First Name"
+person.first_name_was # => nil
```
-Track both previous and current value of the changed attribute. Returns an array if changed, else returns nil.
+Track both previous and current value of the changed attribute. Returns an array
+if changed, else returns nil.
```ruby
# attr_name_change
@@ -175,7 +195,8 @@ person.last_name_change # => nil
### Validations
-Validations module adds the ability to class objects to validate them in Active Record style.
+`ActiveModel::Validations` module adds the ability to validate class objects
+like in Active Record.
```ruby
class Person
@@ -188,7 +209,8 @@ class Person
validates! :token, presence: true
end
-person = Person.new(token: "2b1f325")
+person = Person.new
+person.token = "2b1f325"
person.valid? # => false
person.name = 'vishnu'
person.email = 'me'
@@ -199,9 +221,9 @@ person.token = nil
person.valid? # => raises ActiveModel::StrictValidationFailed
```
-### ActiveModel::Naming
+### Naming
-Naming adds a number of class methods which make the naming and routing
+`ActiveModel::Naming` adds a number of class methods which make the naming and routing
easier to manage. The module defines the `model_name` class method which
will define a number of accessors using some `ActiveSupport::Inflector` methods.
@@ -221,3 +243,312 @@ Person.model_name.i18n_key # => :person
Person.model_name.route_key # => "people"
Person.model_name.singular_route_key # => "person"
```
+
+### Model
+
+`ActiveModel::Model` adds the ability to a class to work with Action Pack and
+Action View right out of the box.
+
+```ruby
+class EmailContact
+ include ActiveModel::Model
+
+ attr_accessor :name, :email, :message
+ validates :name, :email, :message, presence: true
+
+ def deliver
+ if valid?
+ # deliver email
+ end
+ end
+end
+```
+
+When including `ActiveModel::Model` you get some features like:
+
+- model name introspection
+- conversions
+- translations
+- validations
+
+It also gives you the ability to initialize an object with a hash of attributes,
+much like any Active Record object.
+
+```ruby
+email_contact = EmailContact.new(name: 'David',
+ email: 'david@example.com',
+ message: 'Hello World')
+email_contact.name # => 'David'
+email_contact.email # => 'david@example.com'
+email_contact.valid? # => true
+email_contact.persisted? # => false
+```
+
+Any class that includes `ActiveModel::Model` can be used with `form_for`,
+`render` and any other Action View helper methods, just like Active Record
+objects.
+
+### Serialization
+
+`ActiveModel::Serialization` provides a basic serialization for your object.
+You need to declare an attributes hash which contains the attributes you want to
+serialize. Attributes must be strings, not symbols.
+
+```ruby
+class Person
+ include ActiveModel::Serialization
+
+ attr_accessor :name
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+Now you can access a serialized hash of your object using the `serializable_hash`.
+
+```ruby
+person = Person.new
+person.serializable_hash # => {"name"=>nil}
+person.name = "Bob"
+person.serializable_hash # => {"name"=>"Bob"}
+```
+
+#### ActiveModel::Serializers
+
+Rails provides two serializers `ActiveModel::Serializers::JSON` and
+`ActiveModel::Serializers::Xml`. Both of these modules automatically include
+the `ActiveModel::Serialization`.
+
+##### ActiveModel::Serializers::JSON
+
+To use the `ActiveModel::Serializers::JSON` you only need to change from
+`ActiveModel::Serialization` to `ActiveModel::Serializers::JSON`.
+
+```ruby
+class Person
+ include ActiveModel::Serializers::JSON
+
+ attr_accessor :name
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+With the `as_json` you have a hash representing the model.
+
+```ruby
+person = Person.new
+person.as_json # => {"name"=>nil}
+person.name = "Bob"
+person.as_json # => {"name"=>"Bob"}
+```
+
+From a JSON string you define the attributes of the model.
+You need to have the `attributes=` method defined on your class:
+
+```ruby
+class Person
+ include ActiveModel::Serializers::JSON
+
+ attr_accessor :name
+
+ def attributes=(hash)
+ hash.each do |key, value|
+ send("#{key}=", value)
+ end
+ end
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+Now it is possible to create an instance of person and set the attributes using `from_json`.
+
+```ruby
+json = { name: 'Bob' }.to_json
+person = Person.new
+person.from_json(json) # => #<Person:0x00000100c773f0 @name="Bob">
+person.name # => "Bob"
+```
+
+##### ActiveModel::Serializers::Xml
+
+To use the `ActiveModel::Serializers::Xml` you only need to change from
+`ActiveModel::Serialization` to `ActiveModel::Serializers::Xml`.
+
+```ruby
+class Person
+ include ActiveModel::Serializers::Xml
+
+ attr_accessor :name
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+With the `to_xml` you have a XML representing the model.
+
+```ruby
+person = Person.new
+person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<person>\n <name nil=\"true\"/>\n</person>\n"
+person.name = "Bob"
+person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<person>\n <name>Bob</name>\n</person>\n"
+```
+
+From a XML string you define the attributes of the model.
+You need to have the `attributes=` method defined on your class:
+
+```ruby
+class Person
+ include ActiveModel::Serializers::Xml
+
+ attr_accessor :name
+
+ def attributes=(hash)
+ hash.each do |key, value|
+ send("#{key}=", value)
+ end
+ end
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+Now it is possible to create an instance of person and set the attributes using `from_xml`.
+
+```ruby
+xml = { name: 'Bob' }.to_xml
+person = Person.new
+person.from_xml(xml) # => #<Person:0x00000100c773f0 @name="Bob">
+person.name # => "Bob"
+```
+
+### Translation
+
+`ActiveModel::Translation` provides integration between your object and the Rails
+internationalization (i18n) framework.
+
+```ruby
+class Person
+ extend ActiveModel::Translation
+end
+```
+
+With the `human_attribute_name` you can transform attribute names into a more
+human format. The human format is defined in your locale file.
+
+* config/locales/app.pt-BR.yml
+
+ ```yml
+ pt-BR:
+ activemodel:
+ attributes:
+ person:
+ name: 'Nome'
+ ```
+
+```ruby
+Person.human_attribute_name('name') # => "Nome"
+```
+
+### Lint Tests
+
+`ActiveModel::Lint::Tests` allow you to test whether an object is compliant with
+the Active Model API.
+
+* app/models/person.rb
+
+ ```ruby
+ class Person
+ include ActiveModel::Model
+
+ end
+ ```
+
+* test/models/person_test.rb
+
+ ```ruby
+ require 'test_helper'
+
+ class PersonTest < ActiveSupport::TestCase
+ include ActiveModel::Lint::Tests
+
+ def setup
+ @model = Person.new
+ end
+ end
+ ```
+
+```bash
+$ rake test
+
+Run options: --seed 14596
+
+# Running:
+
+......
+
+Finished in 0.024899s, 240.9735 runs/s, 1204.8677 assertions/s.
+
+6 runs, 30 assertions, 0 failures, 0 errors, 0 skips
+```
+
+An object is not required to implement all APIs in order to work with
+Action Pack. This module only intends to provide guidance in case you want all
+features out of the box.
+
+### SecurePassword
+
+`ActiveModel::SecurePassword` provides a way to securely store any
+password in an encrypted form. On including this module, a
+`has_secure_password` class method is provided which defines
+an accessor named `password` with certain validations on it.
+
+#### Requirements
+
+`ActiveModel::SecurePassword` depends on the [`bcrypt`](https://github.com/codahale/bcrypt-ruby 'BCrypt'),
+so include this gem in your Gemfile to use `ActiveModel::SecurePassword` correctly.
+In order to make this work, the model must have an accessor named `password_digest`.
+The `has_secure_password` will add the following validations on the `password` accessor:
+
+1. Password should be present.
+2. Password should be equal to its confirmation.
+3. This maximum length of a password is 72 (required by `bcrypt` on which ActiveModel::SecurePassword depends)
+
+#### Examples
+
+```ruby
+class Person
+ include ActiveModel::SecurePassword
+ has_secure_password
+ attr_accessor :password_digest
+end
+
+person = Person.new
+
+# When password is blank.
+person.valid? # => false
+
+# When the confirmation doesn't match the password.
+person.password = 'aditya'
+person.password_confirmation = 'nomatch'
+person.valid? # => false
+
+# When the length of password, exceeds 72.
+person.password = person.password_confirmation = 'a' * 100
+person.valid? # => false
+
+# When all validations are passed.
+person.password = person.password_confirmation = 'aditya'
+person.valid? # => true
+```
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index 582bb240dd..4dc7203ba3 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -524,9 +524,15 @@ If you validate the presence of an object associated via a `has_one` or
`marked_for_destruction?`.
Since `false.blank?` is true, if you want to validate the presence of a boolean
-field you should use `validates :field_name, inclusion: { in: [true, false] }`.
+field you should use one of the following validations:
-The default error message is _"can't be blank"_.
+```ruby
+validates :boolean_field_name, presence: true
+validates :boolean_field_name, inclusion: { in: [true, false] }
+validates :boolean_field_name, exclusion: { in: [nil] }
+```
+By using one of these validations, you will ensure the value will NOT be `nil`
+which would result in a `NULL` value in most cases.
### `absence`
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index 7b9710bcd8..be0478653b 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -368,24 +368,24 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
```ruby
config.action_dispatch.rescue_responses = {
- 'ActionController::RoutingError' => :not_found,
- 'AbstractController::ActionNotFound' => :not_found,
- 'ActionController::MethodNotAllowed' => :method_not_allowed,
- 'ActionController::UnknownHttpMethod' => :method_not_allowed,
- 'ActionController::NotImplemented' => :not_implemented,
- 'ActionController::UnknownFormat' => :not_acceptable,
- 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
- 'ActionDispatch::ParamsParser::ParseError' => :bad_request,
- 'ActionController::BadRequest' => :bad_request,
- 'ActionController::ParameterMissing' => :bad_request,
- 'ActiveRecord::RecordNotFound' => :not_found,
- 'ActiveRecord::StaleObjectError' => :conflict,
- 'ActiveRecord::RecordInvalid' => :unprocessable_entity,
- 'ActiveRecord::RecordNotSaved' => :unprocessable_entity
+ 'ActionController::RoutingError' => :not_found,
+ 'AbstractController::ActionNotFound' => :not_found,
+ 'ActionController::MethodNotAllowed' => :method_not_allowed,
+ 'ActionController::UnknownHttpMethod' => :method_not_allowed,
+ 'ActionController::NotImplemented' => :not_implemented,
+ 'ActionController::UnknownFormat' => :not_acceptable,
+ 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
+ 'ActionDispatch::ParamsParser::ParseError' => :bad_request,
+ 'ActionController::BadRequest' => :bad_request,
+ 'ActionController::ParameterMissing' => :bad_request,
+ 'ActiveRecord::RecordNotFound' => :not_found,
+ 'ActiveRecord::StaleObjectError' => :conflict,
+ 'ActiveRecord::RecordInvalid' => :unprocessable_entity,
+ 'ActiveRecord::RecordNotSaved' => :unprocessable_entity
}
```
- Any execptions that are not configured will be assigned to 500 Internal server error.
+ Any exceptions that are not configured will be mapped to 500 Internal Server Error.
* `ActionDispatch::Callbacks.before` takes a block of code to run before the request.
diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml
index 5c37837a1c..4c98d3e1d5 100644
--- a/guides/source/documents.yaml
+++ b/guides/source/documents.yaml
@@ -32,6 +32,11 @@
name: Active Record Query Interface
url: active_record_querying.html
description: This guide covers the database query interface provided by Active Record.
+ -
+ name: Active Model basics
+ url: active_model_basics.html
+ description: This guide covers the use of model classes without Active Record.
+ work_in_progress: true
-
name: Views
documents:
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 29724ae011..b784098fbb 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -797,6 +797,7 @@ when you initiate a Rails project.
| `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional` |
| `rake test:helpers` | Runs all the helper tests from `test/helpers` |
| `rake test:integration` | Runs all the integration tests from `test/integration` |
+| `rake test:jobs` | Runs all the job tests from `test/jobs` |
| `rake test:mailers` | Runs all the mailer tests from `test/mailers` |
| `rake test:models` | Runs all the model tests from `test/models` |
| `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit` |