Wynn Netherland changelog.com/posts

active_attr - the stuff ActiveModel left out

Newcomers to Rails often discover too late that not all application models have to be ORM-backed. There are a number of reasons why you might not need or want to persist your models in a data store. Perhaps you want to roll your own persistence layer. In those scenarios, you might miss some conveniences of ActiveRecord-based models. While ActiveModel has made models more consistent between ActiveRecord, Mongoid, and other ORMs, it doesn’t cover every ActiveRecord feature. Bridging this gap is the inspiration behind ActiveAttr, a project from Chris Griego.

ActiveAttr lets you define attributes:

class Person
  include ActiveAttr::Attributes

  attribute :first_name
  attribute :last_name
end

person = Person.new
person.first_name = "Chris"
person.last_name = "Griego"
person.attributes #=> {"first_name"=>"Chris", "last_name"=>"Griego"}

… with defaults

class Person
  include ActiveAttr::Attributes

  attribute :first_name, :default => "John"
  attribute :last_name, :default => "Doe"
end

person = Person.new
person.first_name #=> "John"
person.last_name #=> "Doe"

… even specify assignment security:

class Person
  include ActiveAttr::MassAssignmentSecurity
  attr_accessor :first_name, :last_name
  attr_protected :last_name
end

person = Person.new(:first_name => "Chris", :last_name => "Griego")
person.first_name #=> "Chris"
person.last_name #=> nil

ActiveAttr also supports logging, typecasting, and more. Check out the source on GitHub for more info or to contribute.


Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00