PassiveRecord
October 2nd, 2008
Ever need to use structured data that doesn’t need its own database model? Ryan Bates shows you how in a recent Railscast: Non Active Record Model.
If you have more than one non ActiveRecord model, you’ll find yourself starting to duplicate a lot of code. I did recently, so I extracted a bunch of functionality into a plugin called PassiveRecord.
PassiveRecord provides ActiveRecord-like behavior for static, non-database models.
Let’s say you wanted to have a Name object that you could toss around in a nice little package:
1 2 3 4 5 |
class Name < PassiveRecord define_attributes [:first_name, :middle_name, :last_name] end @name = Name.new(:first_name => "Dima", :last_name => "Dozen") |
Then you could have a Person object that has_many names like this:
1 2 3 4 5 |
class Person < PassiveRecord has_many :names end @person = Person.new(:names => [@name]) |
You can now access the names hash just like you would an ActiveRecord object:
1 2 |
@person.names #=> [#<Name:0x2031824 @last_name="Dozen", @first_name="Dima">] @person.names.first.first_name #=> "Dima" |
You can serialize a PassiveRecord object into another database object for storage:
1 2 3 4 5 6 7 8 9 |
class Address < PassiveRecord define_attributes [:street, :city, :state, :postal_code, :country] end class Company < ActiveRecord serialize :address end @company.address = Address.new(:street1 => "123 4th St", :city => "Wellington", :country => "NZ") |
Check out PassiveRecord on Github: github.com/artofmission/passive_record
2 Responses to “PassiveRecord”
Sorry, comments are closed for this article.
October 2nd, 2008 at 04:59 PM
Cool, just discovered that there’s another PassiveRecord plugin: http://github.com/ambethia/passiverecord/tree/master/. Mine’s a whole lot more basic though.
October 3rd, 2008 at 08:48 AM
Here’s that link: http://github.com/ambethia/passiverecord/tree/master/