Toy Attributes

Toy Attributes is a component of Toy Locomotive, but can be used independently outside Toy Locomotive.

Getting Started

All you need to start using Toy Attributes is to add the following line to your application's Gemfile:

gem "toy-attributes"

Declaring Attributes

This gem allows to assign attributes directly inside ActiveRecord models without having to write migrations. In order to make it happen, your model will have access to the following class methods:

string, text, integer, float, decimal, datetime, timestamp, time, date, binary, boolean, references

Let's say your application is about warriors and all your warriors have a name, the code bellow will do the trick:

class Warrior < ActiveRecord::Base
  string :name
end

With this snippet, Toy Attributes will create the table warriors if it does not exist already, and add the string column name to it. You can also pass more than one column at a time to your method, for example:

class Weapon < ActiveRecord::Base
  integer :min_damage, :max_damage
end

Now both min_damage and max_damage will be present on weapons table's schema and ready to use.

All attributes generated with Toy are declared as attr_accessible, making them mass-assignable.

Dealing with Relations

Toy also deals with model relations in a simple way, so you won't have to worry about their migrations either.

class Warrior < ActiveRecord::Base
  string :name
  has_many :weapons
end

class Weapon < ActiveRecord::Base
  integer :min_damage, :max_damage
end

Note that you won't have to declare that weapon belongs_to a warrior, Toy will automatically generate the foreign key and set up the relation; the same works to has_one relations.

You can also declare multiple relations in a single line and even pass a hash of options:

class Warrior < ActiveRecord::Base
  has_many :weapons, :items, :dependent => :destroy
end

All relations generated by Toy Attributes will accept_nested_attributes_for and receive attr_accessible on related model's attributes.

Changing Columns

At development mode, any change on your models will be automatically detected and instantly applied:

class Weapon < ActiveRecord::Base
  float :min_damage, :max_damage
end

This will result on a change of column type at the very moment it's identified on development mode or in the startup in production mode.

TO-DO

  • Add a rake task to clean unused columns;
  • Allow more options on columns creation;
  • Generate hardcoded migrations on db/migrations and make them reversible;
  • Add support to habtm relations;
  • Make automatic mass-assignment configurable via initializer.