Simple integration of ActiveRecord connections and Rake tasks with Grape. Supports ActiveRecord 4.x. Inspired by sinatra-activerecord (github.com/janko-m/sinatra-activerecord).
gem 'grape-activerecord'
# Use a Hash Grape::ActiveRecord.database = {adapter: 'postgresql', host: 'localhost', database: 'db', username: 'user', password: 'pass', encoding: 'utf8', pool: 10, timeout: 5000} # or a URL Grape::ActiveRecord.database_url = 'postgres://user:pass@localhost/db' # or a YAML file Grape::ActiveRecord.database_file = 'config/database.yml'
If you don’t specify any configuration, grape-activerecord will first look in DATABASE_URL, then in config/database.yml.
class MyApi < Grape::API include Grape::ActiveRecord::Extension ... end
This will establish the database connections and (usually) correctly return used connections to the pool after each request. NOTE If you’re mounting sub Grape apps, you need only include grape-activerecord in the root app.
It’s recommended that you manually include ActiveRecord::ConnectionAdapters::ConnectionManagement yourself BEFORE mounting your Grape app (github.com/intridea/grape/issues/517#issuecomment-60969722). The top of your config.ru file is a good place:
# config.ru use ActiveRecord::ConnectionAdapters::ConnectionManagement run MyGrapeApi
require 'bundler/setup' require 'grape/activerecord/rake' namespace :db do # Some db tasks require your app code to be loaded task :environment do require_relative 'app' end end
This will give you most of the standard “db:” tasks you get in Rails. Run “bundle exec rake -T” to get a full list. Note that unlike in Rails, creating a new migration is also a rake task:
bundle exec rake db:create_migration NAME=create_widgets
Look under /examples for some example apps.