How to Play with Rails ActiveModel in IRB

Install the gem.

gem install activemodel

Create a contact class and mixin ActiveModel.

require 'active_model'

class Contact
  include ActiveModel::Model

  attr_accessor :name

  validates :name, presence: true

We gave defined a name attribute with a validation for it. We can now experiment in the IRB console:

 $ irb
 load './contact.rb'
 c =
 # => false

We need a name for a valid contact object.

bugs = 'Bugs Bunny')
 => true 

The invalid contact has no name.
 => nil 

The valid contact has a name.
 => "Bugs Bunny" 

If you don't provide:

attr_accessor :name

you will get:

NoMethodError: undefined method `name=' for #<Contact:0x004a70>

when you instantiate the object.

bugs = 'Bugs Bunny')


Active Model Rails 4
Document Structure Resource Collection Representations

Related Articles