Slide 1

Slide 1 text

ActiveModel ActiveRecord’s useful stuff Sunday, January 29, 12

Slide 2

Slide 2 text

Gem Spec • Part of Rails gem package • Own standalone gem: • gem ‘activemodel’ • Dependencies: • gem ‘activesupport’ Sunday, January 29, 12

Slide 3

Slide 3 text

ActiveModel Packages • ActiveModel::AttributeMethods • ActiveModel::Callbacks • ActiveModel::Conversion • ActiveModel::Dirty • ActiveModel::Naming • ActiveModel::Observer • ActiveModel::Serialization • ActiveModel::Translation • ActiveModel::Validations Sunday, January 29, 12

Slide 4

Slide 4 text

ActiveModel Packages • ActiveModel::AttributeMethods • ActiveModel::Callbacks • ActiveModel::Conversion • ActiveModel::Dirty • ActiveModel::Naming • ActiveModel::Observer • ActiveModel::Serialization • ActiveModel::Translation • ActiveModel::Validations Sunday, January 29, 12

Slide 5

Slide 5 text

Validations • Most Rails validations originate from ActiveModel • Including ActiveModel::Validations gives you • #valid? • #errors • Class methods for validation API Sunday, January 29, 12

Slide 6

Slide 6 text

Validations API • validates_acceptance_of • validates_confirmation_of • validates_each • validates_format_of • validates_inclusion_of declarative • validates_exclusion_of • validates_length_of • validates_numericality_of • validates_presence_of • validates_with Sunday, January 29, 12

Slide 7

Slide 7 text

Validations API short form • validates :field_name, :validator => options Sunday, January 29, 12

Slide 8

Slide 8 text

Validation API • validates_each :field_name, &block • validate :method_name • validate &block • validates_with ValidatorClass Sunday, January 29, 12

Slide 9

Slide 9 text

Callbacks • In ActiveRecord, this is how before_create, after_create and around_create are made. • Two different steps: register callbacks and execute callbacks. Sunday, January 29, 12

Slide 10

Slide 10 text

Observers • Use observers to decouple logic from models. • Observers use convention to identify targets: ModelObserver observes Model unless explicitly overridden. Sunday, January 29, 12

Slide 11

Slide 11 text

Serialization • Allows for models to define how they would like to be serialized in a variety of formats (including XML and JSON). • Important for creation of presenters that get sent as JSON in RESTful API. Sunday, January 29, 12

Slide 12

Slide 12 text

Dirty • ActiveModel provides an API for detecting whether an object is “dirty” or not (changed). • Could be useful for operations that may or may not be idempotent and you need to know which (e.g. marking a message as read). Sunday, January 29, 12

Slide 13

Slide 13 text

Questions? Sunday, January 29, 12