Active Model is a Rails library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. This came about by extracting common functionality that was not persistence specific out of Active Record, so that 3rd party libraries did not have to copy code from Rails or monkey patch helpers in order to conform to the API.
Out of this extraction came extremely useful reusable functionality to developers of Rails compatible libraries, such as dirty attributes, validations, and serialization into JSON or XML. And simply by using these modules developers could be DRY and not need to rewrite what has already been done before.
Section headings reflect the name of the Class or Module where the API method is located and are organized in alphabetical order for easy lookup. Sub-sections appear according to the name of the Ruby file in which they exist within Active Model’s lib
directory. Finally, the sub-sub-sections are the API methods themselves.
AttributeMethods
AttributeMethods
adds the ability for your class to have custom prefixes and suffixes on your methods. It is used by adding the definitions for the prefixes and suffixes, defining which methods on the object will use them, then implementing the common behavior for when those methods are called. An example implementation is as follows:
active_model/attribute_methods.rb
attribute_method_affix(*affixes)
Defines a prefix and suffix that when used in conjuction with define_attribute_methods
creates a instance method with the prefix and suffix wrapping the previous method name.
attribute_method_prefix(*prefixes)
Defines a prefix that when used in conjuction with define_attribute_methods
creates a instance method with the prefix and the previous method name.
attribute_method_suffix(*suffixes)
Defines a suffix that when used in conjuction with define_attribute_methods
creates a instance method with the suffix and the previous method name.
attribute_methods_generated?
Returns whether or not the dynamic attribute methods have been generated.
define_attr_method(name, value = nil, & block)
Defines an attribute method, which is a class method that replaces an existing method and prefixes the original method with original_
. This is so the newmethod can access the original value.
define_attribute_methods(*attr_names)
Defines the methods that will get prefixed and suffixed.
undefine_attribute_methods
Removes all the attribute method definitions
Callbacks
Callbacks
gives any class Active Record–style callbacks. It is used by defining the callbacks that the model will use, then in your model running the callbacks at the appropriate time. Once defined you have access to before
, after
, and around
custom methods.
active_model/callbacks.rb
define_model_callbacks(*callbacks)
Defines the callback hooks that can be used in the model, which will dynamically provide you with a before
, after
, and around
hook for each name passed. Can optionally supply an :only
option to specify which of those you want executed.
Conversion
Conversion
is a simple module that when included gives the standard Rails conversion methods to your model. The only requirement for including this class is that your model contains a persisted?
method and an id
method.
active_model/conversion.rb
to_model
Returns self. If your model is not Active Model compliant, then override this method.
to_key
Will either return an array of primary key attributes or nil if the object is not persisted.
to_param
Will return a url friendly version of the primary or nil if the object is not persisted.
Dirty
Dirty
is a powerful module that allows for tracking in your object what changes have been made to it since it was last initialized. It creates a handful of dynamic methods based on which attributes you define as attribute methods on your class, and requires that you also tell the attribute setters that they are being tracked for changes. (You can optionally also store previous changes each time your object is presisted as well.)
In the example above, the following dynamic methods would then be available for checking the dirty state of the flagged field. (Assume user is an instance of the User class.)
active_model/dirty.rb
changed
Gets an array of fields whos values have changed on the object.
changed?
Returns whether or not the object’s attributes have changed.
changed_attributes
Returns a Hash of the fields that have changed with their original values.
changes
Returns a Hash of changes, with the attribute names as the keys, and the values being an array of the old and new value for that field.
previous_changes
Returns a Hash of previous changes before the object was persisted, with the attribute names as the keys, and the values being an array of the old and new value for that field.
Errors
Errors
is a class that provides a common interface for handling application error messages.
Note that in order for your object to be compatible with the Errors
API with i18n and validations support, it needs to extend ActiveModel::Naming
, ActiveModel::Translations
, and include ActiveModel::Validations
.
active_model/errors.rb
[](attribute)
Returns the errors for the supplied attribute as an array.
[]=(attribute, error)
Adds the provided error message to the attribute’s errors.
add(attribute, message = nil, options = {})
Adds an error message for the supplied attribute. If no message is provided, :invalid
is assumed. Options allowed are:
:default
A default message for the error.
add_on_blank(attributes, custom_message = nil)
Adds an error message for each provided blank attribute name.
add_on_empty(attributes, custom_message = nil)
Adds an error message for each provided empty attribute name.
count
Returns the total number of error messages.
each
Iterates through the error keys, yielding the attribute and the errors for each.
empty?
Returns whether or not any errors exist.
full_messages
Returns all the error messages as an array.
generate_message(attr, message = :invalid, options = {})
Generates a translated error message for the supplied attribute. Messages are looked up via the following pattern: models.MODEL.attributes.ATTRIBUTE.MESSAGE
. Options provided can be:
:default
A default message for the error.
size
Returns the total number of error messages.
to_a
Returns an array of all the error messages, with the attribute name included in each.
to_xml
Returns the errors hash as XML.
Lint::Tests
You can check whether an object is compatible with the Active Model API by including ActiveModel::Lint::Tests
. It contains assertions that tell you whether your object is fully compliant.
The tests only check compatibility. They do not attempt to determine the correctness of the returned values. For instance, you could implement valid?
to always return true and the tests would still pass. It is up to you to ensure that the values are correct.
Objects you pass in are expected to return a compliant object from a call to to_model
. Generally speaking, to_model
just returns self
.
MassAssignmentSecurity
MassAssignmentSecurity
is a module that can be included to provided protected and accessible access to your attributes. Mass assignment is defined in Rails as any method or constructor that allows more than one value to be set at the same time. The methods provided in this module help prevent fields such as ids and passwords to get accidentally set through the likes of form submissions, etc.
User.new(:first_name => "Joe", :last_name => "Smith")
Account.create(:name => "Acme")
active_model/mass_assignment_security.rb
attr_protected
Attributes defined as protected do not get their values set when a mass assignment method is called.
attr_accessible
Defines a list of attributes that can be set via mass assignment, all others will be protected by default.
Name
Name
extends String
and wraps a bunch of logic around name information about your object so that it can be used with Rails.
How much name information could there be? Take a look at Name
’s constructor.
All of this information is calculated and stored at initialization-time, presumably since it’s used all over Rails.
active_model/naming.rb
collection
Returns an underscored plural version of the model name.
element
Returns an underscored version of the model name.
human
Returns a translated human readable version of the model name using I18n. The basic recipe is to capitalized the first word of the name.
BlogPost.model_name.human # => "Blog post"
partial_path
Returns collection/element
.
plural
Returns a pluralized version of the model name.
singular
Returns a singularized version of the model name.
Naming
Naming
is the module that you include in your class to get name type information for your model.
active_model/naming.rb
model_name
Returns an ActiveModel::Name
for the object. Used by Action Pack to determine routing
Observer
Observer
is the class to inherit from when creating your own observer to hook into the lifecycle of your models. In order for it to work properly, the model to observe must include ActiveModel::Observing
, and the observers must be set up in an initializer or similar.
active_model/observing.rb
observe(*models)
Tells what models this observer observes. This is useful when the naming does not match the model name or multiple objects need to be observed. The models can be classes or symbols.
observed_class
Returns the default observed class.
observe_class_inherited(subclass)
Sets up the observer to watch subclasses of the observed model.
observed_classes
Returns an array of the classes this observer observes.
update(observed_method, object)
Calls the supplied method with the object as the args if the method exists.
Observing
Observing
is a module to include in your models to set up observers in the lifecycle of your model. Observers are added to the class by calling the observers class method at some point in the application bootstrapping. An initializer would be a good fit for this.
active_model/observing.rb
add_observer(observer)
Adds an instantiated observer to the class.
count_observers
Returns the number of observers the class has.
instantiate_observers
Instantiate each of the class’ observers.
notify_observers(*args)
Iterates through all the class’ observers and calls update on them.
observers
Get the observers for the class.
Serialization
Serialization
is a module to include in your models when you want to represent your model as a serializable hash. You only need to define an attributes
method and the rest is handled for you.
active_model/serialization.rb
serializable_hash(options = nil)
Returns the serializable hash representation of your model. Options provided can be of the following:
:except
Do not include these attributes in the XML.
:methods
Only include these methods in the XML.
:only
Only include the supplied attributes.
Serializers::JSON
Serializers::JSON
is a module to include in your models when you want to provide a JSON representation of your object. It autmatically includes the Serialization
module and depends on the attributes
and attributes=
methods to be present.
active_model/serializers/json.rb
as_json(options = nil)
Returns a hash to convert to JSON for the model attributes.
from_json(json)
Decodes the supplied JSON, sets the attributes on the model, and returns self.
Serializers::Xml
Serializers::Xml
is a module to include in your models when you want to provide an XML representation of your object. It automatically includes the Serialization
module and depends on the attributes
and attributes=
methods to be present.
active_model/serializers/xml.rb
to_xml(options = {}, & block)
Returns an XML representation of the object. Available options are:
:builder
Supply a custom builder to generate the markup.
:except
Do not include these attributes in the XML.
:indent
Number of spaces to indent the XML.
:methods
Only include these methods in the XML.
:namespace
Set the XMLNS.
:only
Only include the supplied attributes.
:skip_instruct
Skip processing instructions.
:skip_types
Skip typing.
:type
Add a type to the XML tags.
from_xml(xml)
Decodes the supplied XML, sets the attributes on the model, and returns self.
Translation
Translation
provides the ability to add internationalization support to your model
class User
extend ActiveModel::Translation
end
active_model/translation.rb
i18n_scope
Returns :activemodel, you can override if you want a custom namespace.
lookup_ancestors
Gets all ancestors of this class that support i18n.
human_attribute_name(attribute, options = {}
Translates attribute names into a human readable format with options.
:default
The default text for the attribute name.
Validations
Validations
adds a fully featured validations framework to your model. This includes the means to validate the following types of scenarios plus the ability to create custom validators.
Acceptance of a field.
Confirmation of a field.
Exclusion of a field from a set of values.
Format of a field against a regular expression.
Inclusion of a field in a set of values.
Length of a field.
Numericality of a field.
Presence of a field.
active_model/validations.rb
Note that available base options for validation macros that use options are as follows. If the specific validation has additional options they will be explained there. All options are supplied as a Hash, and are the last element of the first set of arguments to the macros.
:allow_nil
Specify whether to validate nil attributes.
:if
Only run if the supplied method or proc returns true.
:on
Define when the validation will run.
:unless
Only run if the supplied method or proc returns false.
attribute_method?(attribute)
Returns true if a method is defined for the supplied attribute.
errors
Get all the errors for the model.
invalid?(context = nil)
Checks if the object is invalid given the optional context.
valid?(context = nil)
Checks if the object is valid given the optional context.
validate(*args, & block)
Adds a single validation to the model. Can be a method name as a symbol or a block with options. Additional options are:
:allow blank
Specify whether to validate blank attributes.
validates_acceptance_of(*args)
Validates that a field was accepted.
validates_acceptance_of :terms, :on => :create
Additional Options:
:message
An optional custom error message.
:accept
Provide the value that is considered accepted.
validates_confirmation_of(*args)
Validates that a field was confirmed.
validates_confirmation_of :password, :message => "Please try again."
Additional Options:
:message
An optional custom error message.
validates_each(*attrs, & block)
Validates each of the attribute names against the supplied block. Options are passed in as a Hash as the last element in the *attrs argument.
:allow blank
Specify whether to validate blank attributes.
validates_exclusion_of(*args)
Validates that a field does not have a value supplied in the list.
validates_exclusion_of :age, :in => 18..55
:in
The list or range the check the value against.
:message
An optional custom error message.
validates_format_of(*args)
Validates that a field conforms to the supplied format.
validates_format_of :phone, :with => /A[d-()sx]+z/
Additional Options:
:allow blank
Specify whether to validate blank attributes.
:with
The regular expression to check if the format matches.
:without
The regular expression to check that the format does not match.
:message
An optional custom error message.
validates_inclusion_of(*args)
Validates that a field is a value supplied in the list.
validates_inclusion_of :state, :in => [ "CA", "NY" ]
Additional Options:
:allow blank
Specify whether to validate blank attributes.
:in
The list or range the check the value against.
:message
An optional custom error message.
validates_length_of(*args)
Validates that a field adheres to the supplied length limitations.
validates_length_of :name, :maximum => 48
Additional Options:
:allow blank
Specify whether to validate blank attributes.
:in
Specify the range the length of the attribute can fall within.
:maximum
Specify the maximum length of the attribute.
:message
An optional custom error message.
:minimum
Specify the minimum length of the attribute.
:tokenizer
A block to define how the string should be broken up.
:too_long
Define a custom message if the attribute is too long.
:too_short
Define a custom message if the attribute is too short.
:within
Specify the range the length of the attribute can fall within.
:wrong_length
Define a custom message for an incorrect length.
validates_numericality_of(*args)
Validates that a field is numeric and optionally in a specified value range.
validates_numericality_of :score, :only_integer => true
Additional Options:
:equal_to
Specify a value the field must be exactly.
:even
Set that the value must be even.
:greater_than
Specify a value the field must be greater than.
:greater_than_or_equal_to
Specify a value the field must be greater than or equal to.
:less_than
Specify a value the field must be less than.
:less_than_or_equal_to
Specify a value the field must be less than or equal to.
:message
An optional custom error message.
:odd
Set that the value must be odd.
:only_integer
Set whether the value has to be an integer.
validates_presence_of(*args)
Validates that a field is not blank.
validates_presence_of :dob
Additional Options:
:message
An optional custom error message.
validates_with(*args, & block)
Validates with a supplied custom validator. The validator class must respond to validate
and handle the options and error message addition internally.
validators
Get all the validators being used by the class.
validators_on(attribute)
Get all the validators for a specific attribute.
Validator
Validator
provides a class that custom validators can extend to seamlessly integrate into the ActiveModel::Validations
API. It only requires that the new class defines a validate
method.
A full explanation of how to use Validator
and EachValidator
is provided in Section 8.6 “Custom Validation Techniques”.
active_model/validator.rb
kind
Returns the type of the validator, which is a symbol of the underscored class name without “Validator” included.
validate(record)
This method must be overwritten in the validator in order to actually handle the validation itself.
18.191.235.62