Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Last active January 5, 2016 17:09
Show Gist options
  • Save emad-elsaid/5939334 to your computer and use it in GitHub Desktop.
Save emad-elsaid/5939334 to your computer and use it in GitHub Desktop.
add apartment to your project - active admin adapter included this code will create databases and drop them when you create accounts
1- add to gemfile
gem 'apartment'
2- execute
bundle install
rails g scaffold account url:string name:string phone:string email:string address:text ssn:string valid_until:date
rake db:migrate
3- replace app/models/account.rb
4- use the authorization adapter if you were using active admin
5- create the apartment.rb initializer
6- add the line below to config/application.rb
config.middleware.use 'Apartment::Elevators::FirstSubdomain'
7- modify your database.yml to use a user who can create and drop databases
8- create a new rake task db.rake to use "rake db:migrateall" to migrate all available databases
Have Fun!
# app/models/account.rb
class Account < ActiveRecord::Base
attr_accessible :address, :email, :name, :phone, :ssn, :url, :valid_until
attr_readonly :url
validates_presence_of :url, :valid_until
validates_uniqueness_of :url
after_create :after_create_record
before_destroy :before_destroy_record
def after_create_record
Apartment::Database.create(url)
end
def before_destroy_record
Apartment::Database.drop(url)
end
def self.current
find_by_url(Apartment::Database.current_database)
end
def expired?
valid_until < Date.today
end
def expire_within?(days)
valid_until < Date.today + days
end
def grace?
expired? and valid_until+7.days >= Date.today
end
end
# config/initializers/apartment.rb
Apartment.configure do |config|
config.seed_after_create = true
config.excluded_models = ['Account']
config.default_schema = '<your default database name here>'
end
# lib/tasks/db.rake
namespace :db do
desc "migrate all databases using Apartment migrator"
task :migrateall => :environment do
puts "Started migration for all databases"
dbs = Account.pluck(:url)
puts "Found #{dbs.size} to migrate"
dbs.each do |db|
puts "Migrating database #{db}..."
Apartment::Migrator.migrate db
end
puts "Databases migrated successfully"
end
end
# app/models/OnlyAdminsAuthorization.rb
class OnlyAdminsAuthorization < ActiveAdmin::AuthorizationAdapter
def authorized?(action, subject = nil)
classname = (subject.is_a? Class)? subject.name : subject.class.name
account = Account.current
# check if expired
if !is_root_db? and account.expired?
if classname!='ActiveAdmin::Page'
return false
elsif subject.name!='Dashboard'
return false
end
end
# if valid then show and hide depend on role and DB
case classname
when AdminUser.name
user.is_admin?
when Account.name
is_root_db?
else
true
end
end
def is_root_db?
Apartment.default_schema == Apartment::Database.current_database
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment