Mobb ActiveRecord Extension
Extends Mobb with extension methods and Rake
tasks for dealing with an SQL database using the
ActiveRecord ORM.
Setup
Put it in your Gemfile
, along with the adapter of your database. For
simplicity, let's assume you're using SQLite:
gem "mobb-activerecord"
gem "sqlite3"
gem "rake"
Now require it in your Mobb application, and establish the database
connection:
require "mobb/activerecord"
set :database, {adapter: "sqlite3", database: "foo.sqlite3"}
If you have a config/database.yml
, it will automatically be loaded, no need
to specify it. Also, in production, the $DATABASE_URL
environment variable
will automatically be read as the database (if you haven't specified otherwise).
Note that in modular Mobb applications you will need to first register
the extension:
class YourApplication < Mobb::Base
register Mobb::ActiveRecordExtension
end
Now require the rake tasks and your app in your Rakefile
:
require "mobb/activerecord/rake"
namespace :db do
task :load_config do
require "./app"
end
end
In the Terminal test that it works:
$ bundle exec rake -T
rake db:create
rake db:create_migration
rake db:drop
rake db:fixtures:load
rake db:migrate
rake db:migrate:status
rake db:rollback
rake db:schema:dump
rake db:schema:load
rake db:seed
rake db:setup
rake db:structure:dump
rake db:version
And that's it, you're all set :)
Usage
You can create a migration:
$ bundle exec rake db:create_migration NAME=create_users
This will create a migration file in your migrations directory (./db/migrate
by default), ready for editing.
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
end
end
end
Now migrate the database:
$ bundle exec rake db:migrate
You can also write models:
class User < ActiveRecord::Base
validates_presence_of :name
end
You can put your models anywhere you want, only remember to require them if
they're in a separate file, and that they're loaded after require "mobb/activerecord"
.
Now everything just works:
on 'list users' do
users = User.all
users.map{ |u| "- #{u.name}"}.join("\n")
end
on /user (\w+)/ do |name|
user = User.find_by(name: name)
"#{user.id} : #{user.name}"
end
A nice thing is that the ActiveRecord::Base
class is available to
you through the database
variable:
if database.table_exists?('users')
else
raise "The table 'users' doesn't exist."
end
History
This gem was made in 2009 by Blake Mizerany, creator of Sinatra.
And forked by Janko Marohnić to improve on.
Social
You can follow me on Twitter, I'm @GhostBrain.
License
MIT