Using ActiveRecord outside of rails

just the rake

Published January 2, 2022 #activerecord, #ruby

Install dependancies

  brew install postgres

Then

  bundle init
  bundle add activerecord pg activerecord rake

Rakefile

Rakefile:

  # From https://gist.github.com/Rhoxio/ee9a855088c53d447f2eb888bd9d09a4
  require "active_record"
  require "fileutils"
  begin
    require 'dotenv/load'
  rescue LoadError
  end

  FileUtils.mkdir_p "db/migrate"

  namespace :db do
    include ActiveRecord::Tasks

    def db_config
      connection.db_config
    end

    def connection
      puts "Database url #{ENV['DATABASE_URL']}"

      @connection ||= ActiveRecord::Base.establish_connection
    end

    desc "Create the database"
    task :create do
      ActiveRecord::Tasks::DatabaseTasks.create db_config
    end


    desc "Migrate the database"
    task :migrate => [:create] do
      connection
      ActiveRecord::MigrationContext.new( 'db/migrate' ).migrate
      Rake::Task["db:schema"].invoke
    end

    desc "Drop the database"
    task :drop do
      connection
      ActiveRecord::Tasks::DatabaseTasks.drop db_config
    end

    desc "Reset the database"
    task :reset => [:drop, :create, :migrate]

    desc 'Create a db/schema.rb file that is portable against any DB supported by AR'
    task :schema do
      ActiveRecord::Tasks::DatabaseTasks.db_dir = './db'
      ActiveRecord::Tasks::DatabaseTasks.dump_schema( db_config )
    end
  end

  namespace :g do
    desc "Generate migration"
    task :migration do
      name = ARGV[1] || raise("Specify name: rake g:migration your_migration")
      timestamp = Time.now.strftime("%Y%m%d%H%M%S")
      path = File.expand_path("../db/migrate/#{timestamp}_#{name}.rb", __FILE__)
      migration_class = name.split("_").map(&:capitalize).join

      File.open(path, 'w') do |file|
        file.write <<-EOF
  class #{migration_class} < ActiveRecord::Migration[6.0]
    def self.up
    end

    def self.down
    end
  end
        EOF
      end

      puts "Migration #{path} created"
      abort # needed stop other tasks
    end
  end

Now

echo rake -T
rake db:create    # Create the database
rake db:drop      # Drop the database
rake db:migrate   # Migrate the database
rake db:reset     # Reset the database
rake db:schema    # Create a db/schema.rb file that is portable against any DB supported by AR
rake g:migration  # Generate migration

References

  1. https://www.devdungeon.com/content/ruby-activerecord-without-rails-tutorial

Read next

See also

Database Migrations

what should I do when not using rails

Keeping track of database changes over time is best done using database migrations stored in a code repository. I'm working on something where programs in different languages will be access the same database, so here we are going to look at 3 different solutions to track changes that aren't tied to a specific framework. We're going to setup a postgres database – with pgadmin so we can see what's going on – and then do the same execersizes with 3 different ways to manage changes.

Read more

Receiving posted JSON with Sinatra

small tricks to make things easier

Here’s some simple code to accept a JSON string posted to a Sinatra end point rather than a form. I switched from using jQueries $.ajax method to superagent as part of my exploration of the node javascript package universe, and it has a different way of serializing nest objects when posting as a form. Specifically, it doesn’t. I needed something that could do both. Code to use form encoding or JSON blob This first tries and loads the parameters using the normal form encoding methods.

Read more

Adding search to a middleman blog

slightly simplier than google

We’re going to build a simple, niave search for middleman blogs. We’re going to build a search index at build time, and then use that index to perform the search itself on the client side. Building the index When you typed in something in google, it doesn’t then go and hit every page on the internet to check to see if there’s a match. It doesn’t even look at every page that it has squirreled away somewhere in the googleplex.

Read more