Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Replacing Rails Components | 279

(See Chapter 2 for a full explanation ofDependencies.) We load all the Ruby files
inapp/models so thatObjectSpace can find them.


  1. We start Og, loading its database adapter configuration from the traditional
    config/database.yml. The Og manager (an instance ofOg::Manager) is stored in
    the global variable$og. We do not typically need to use this manager directly; it
    finds and injects functionality to (“enchants,” in Og lingo) our model classes.
    The exception is if we need two or more database connections. Each manager is
    limited to one database connection, so if we need more connections, we need to
    create more managers.


The database connection syntax is similar to ActiveRecord’s, but there are some dif-
ferences. A basic configuration using SQLite3 and a database file oftodo_list.dbhas
the following syntax:


config/database.yml
development:
adapter: sqlite
name: todo_list


Now we are ready to create model classes. Like DataMapper, Og requires us to
define all attributes to be mapped to the database. Also like DataMapper, Og creates
our schema automatically. Here are some model classes for a very simple to-do list:


app/models/todo_list.rb
class TodoList
attr_accessor :name, String


# Orderable is like ActiveRecord's acts_as_list.
# Equivalent to:
# include Og::Mixin::Orderable
# or (as Og::Mixin is included at the top level)
# include Orderable
is Orderable

has_many :todo_list_items, TodoListItem
end

app/models/todo_list_item.rb
class TodoListItem
attr_accessor :name, String


belongs_to :todo_list, TodoList
is Orderable, :scope => :todo_list
end

Now we can open up the Rails console and start playing with the model classes we
have created.

Free download pdf