Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ActiveModel

 ActiveModel

A deep dive into ActiveModel (v3.1)

Derek Hammer

January 29, 2012
Tweet

More Decks by Derek Hammer

Other Decks in Programming

Transcript

  1. Gem Spec • Part of Rails gem package • Own

    standalone gem: • gem ‘activemodel’ • Dependencies: • gem ‘activesupport’ Sunday, January 29, 12
  2. ActiveModel Packages • ActiveModel::AttributeMethods • ActiveModel::Callbacks • ActiveModel::Conversion • ActiveModel::Dirty

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

    • ActiveModel::Naming • ActiveModel::Observer • ActiveModel::Serialization • ActiveModel::Translation • ActiveModel::Validations Sunday, January 29, 12
  4. Validations • Most Rails validations originate from ActiveModel • Including

    ActiveModel::Validations gives you • #valid? • #errors • Class methods for validation API Sunday, January 29, 12
  5. 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
  6. Validation API • validates_each :field_name, &block • validate :method_name •

    validate &block • validates_with ValidatorClass Sunday, January 29, 12
  7. 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
  8. Observers • Use observers to decouple logic from models. •

    Observers use convention to identify targets: ModelObserver observes Model unless explicitly overridden. Sunday, January 29, 12
  9. 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
  10. 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