active-model v1.1.0

A rails-esque model framework for crystal lang


  • v1.1.0 - February 7, 2019
  • v1.0.1 - March 12, 2018
  • v1.0.0 - March 8, 2018
  • v0.1.0 - February 3, 2018


Spider-Gazelle ActiveModel

Build Status

Active Model provides a known set of interfaces for usage in model classes. Active Model also helps with building custom ORMs.


Please also checkout the detailed guide.

Active Model

ActiveModel::Model should be used as the base class for your ORM

require "active-model"

class Person < ActiveModel::Model
  attribute name : String = "default value"
  attribute age : Int32

p = Person.from_json("\"name\": \"Bob Jane\"") # => "Bob Jane"
p.to_json # => "\"name\":\"Bob Jane\""
p.attributes # => {:name => "Bob Jane", :age => nil}

p.age = 32
p.attributes # => {:name => "Bob Jane", :age => 32}

The attribute macro takes two parameters. The field name with type and an optional default value.


ActiveModel::Validators is a mix-in that you include in your class. Similar to those supported by Rails:

require "active-model"

class Person < ActiveModel::Model
  include ActiveModel::Validation

  attribute name : String
  attribute age : Int32

  validates :name, presence: true, length: { minimum: 3 }
  validates :age, presence: true, numericality: {greater_than: 5}

The validate macro takes three parameters. The symbol of the field and the message that will display when the validation fails. The third is a Proc that is provided an instance of self and returns either true or false.

To check to see if your instance is valid, call valid?. Each Proc will be called and if any of them fails, an errors Array with the messages is returned.

If no Symbol is provided as a first parameter, the errors will be added to the :base field.

person = "JD")
person.valid?.should eq false
person.errors[0].to_s.should eq "Name is too short"

Dirty Checking

Changes to attributes are tracked throughout the lifetime of the model. Similar to Rails:

person = "JD")
person.changed? # => true
person.changed_attributes # => {:name => "JD"}
person.name_changed? # => true
person.name_change # => {nil, "JD"}
person.name_was # => nil

person.changed? # => false


Register before/after callbacks for create, update, delete, save methods. You must define the method you wish to register callbacks for.
Registered callbacks are invoked through wrapping crud logic with the run_create_callbacks, run_update_callbacks, etc. functions

require "active-model"

class Person < ActiveModel::Model
  include ActiveModel::Callbacks

  attribute name : String
  attribute age : Int32

  before_save :capitalize

  def capitalize
    @name = @name.capitalize

  def save
    run_save_callbacks do
      # save to database
Github statistic:
  • 5
  • 0
  • 1
  • 1
  • 15 days ago


MIT License