Module: ActiveModel::API

Extended by:
ActiveSupport::Concern
Includes:
AttributeAssignment, Conversion, Validations
Included in:
Model
Defined in:
lib/active_model/api.rb

Overview

Active Model API

Includes the required interface for an object to interact with Action Pack and Action View, using different Active Model modules. It includes model name introspections, conversions, translations, and validations. Besides that, it allows you to initialize the object with a hash of attributes, pretty much like Active Record does.

A minimal implementation could be:

class Person
  include ActiveModel::API
  attr_accessor :name, :age
end

person = Person.new(name: 'bob', age: '18')
person.name # => "bob"
person.age  # => "18"

Note that, by default, ActiveModel::API implements #persisted? to return false, which is the most common case. You may want to override it in your class to simulate a different scenario:

class Person
  include ActiveModel::API
  attr_accessor :id, :name

  def persisted?
    self.id.present?
  end
end

person = Person.new(id: 1, name: 'bob')
person.persisted? # => true

Also, if for some reason you need to run code on initialize ( ::new ), make sure you call super if you want the attributes hash initialization to happen.

class Person
  include ActiveModel::API
  attr_accessor :id, :name, :omg

  def initialize(attributes={})
    super
    @omg ||= true
  end
end

person = Person.new(id: 1, name: 'bob')
person.omg # => true

For more detailed information on other functionalities available, please refer to the specific modules included in ActiveModel::API (see below).

Instance Method Summary collapse

Methods included from Conversion

#to_key, #to_model, #to_param, #to_partial_path

Methods included from Validations

#errors, #freeze, #initialize_dup, #invalid?, #valid?, #validate!, #validates_with, #validation_context

Methods included from AttributeAssignment

#assign_attributes, #attribute_writer_missing

Instance Method Details

#initialize(attributes = {}) ⇒ Object

Initializes a new model with the given params.

class Person
  include ActiveModel::API
  attr_accessor :name, :age
end

person = Person.new(name: 'bob', age: '18')
person.name # => "bob"
person.age  # => "18"


80
81
82
83
84
# File 'lib/active_model/api.rb', line 80

def initialize(attributes = {})
  assign_attributes(attributes) if attributes

  super()
end

#persisted?Boolean

Indicates if the model is persisted. Default is false.

class Person
  include ActiveModel::API
  attr_accessor :id, :name
end

person = Person.new(id: 1, name: 'bob')
person.persisted? # => false

Returns:

  • (Boolean)


95
96
97
# File 'lib/active_model/api.rb', line 95

def persisted?
  false
end