active_recordをrails以外で使う

ググるとActive Recordを単独で使う方法が出てきますが、手元のRails7系のActive Recordだと動かなかったので、調べながらやってみました。

結論

以下で動きました。

# Rakefile
require "bundler/gem_tasks"
require "bundler/setup"

require "active_record"
require "erb"

include ActiveRecord::Tasks # rubocop:disable Style/MixinUsage

root_dir = File.dirname(__FILE__)
database_config_path = File.join(root_dir, "config/database.yml")
database_config = YAML.safe_load(ERB.new(File.read(database_config_path)).result, aliases: true)

DatabaseTasks.database_configuration = database_config
DatabaseTasks.db_dir = "db"
DatabaseTasks.env = "development"
DatabaseTasks.migrations_paths = "db/migrate"
DatabaseTasks.root = root_dir

task :environment do
  ActiveRecord::Base.configurations = database_config
  ActiveRecord::Base.establish_connection :development
end

load "active_record/railties/databases.rake"

補足

ActiveRecord::Tasks::DatabaseTasks

ActiveRecord::Tasks::DatabaseTasks
migrateに関するロジックがカプセル化してまとめられているとのこと。

Example usage of DatabaseTasks outside Rails could look as such:

include ActiveRecord::Tasks
DatabaseTasks.database_configuration = YAML.load_file('my_database_config.yml')
DatabaseTasks.db_dir = 'db'
# other settings...

DatabaseTasks.create_current('production')

other settingsのところは、リンク先にそれぞれ記載されています。

active_record/railties/databases.rake

rails/databases.rake at v7.0.4.3 · rails/rails
これをloadすることでrails同様にActive Recordが利用できるようになります。便利。

$ bundle exec rake -T db
rake db:create              # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all data...
rake db:drop                # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases ...
rake db:encryption:init     # Generate a set of keys for configuring Active Record encryption in a given environment
rake db:environment:set     # Set the environment value for the database
rake db:fixtures:load       # Loads fixtures into the current environment's database
rake db:migrate             # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:down        # Runs the "down" for a given migration VERSION
rake db:migrate:redo        # Rolls back the database one migration and re-migrates up (options: STEP=x, VERSION=x)
rake db:migrate:status      # Display status of migrations
rake db:migrate:up          # Runs the "up" for a given migration VERSION
rake db:prepare             # Runs setup if database does not exist, or runs migrations if it does
rake db:reset               # Drops and recreates all databases from their schema for the current environment and loads the seeds
rake db:rollback            # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear  # Clears a db/schema_cache.yml file
rake db:schema:cache:dump   # Creates a db/schema_cache.yml file
rake db:schema:dump         # Creates a database schema file (either db/schema.rb or db/structure.sql, depending on `ENV['SCHEMA_FORMAT']` or `config.activ...
rake db:schema:load         # Loads a database schema file (either db/schema.rb or db/structure.sql, depending on `ENV['SCHEMA_FORMAT']` or `config.active_...
rake db:seed                # Loads the seed data from db/seeds.rb
rake db:seed:replant        # Truncates tables of each database for current environment and loads the seeds
rake db:setup               # Creates all databases, loads all schemas, and initializes with the seed data (use db:reset to also drop all databases first)
rake db:version             # Retrieves the current schema version number

RUBYOPT=-W:deprecated 環境変数を設定しておこう

古いruby2.7系のアプリを3.1.2に更新する作業をしていました。

rubyのでdeprecated warningについて

ruby2.7.1 でキーワード引数関係のdeprected warningが沢山出るようになったののを受けて ruby2.7.2 では、deprecated warningをデフォルト非表示にする対応が入っていました。

この辺かな。 Feature #16345: Don't emit deprecation warnings by default. - Ruby master - Ruby Issue Tracking System https://bugs.ruby-lang.org/issues/16345

とりあえず有効化しておこう

多くのライブラリは、ruby3への更新が行われ、現在は大量にwarningが出ることは無くなったので、有効化しておくのが良いでしょう。 当時も、ruby2.7.4に無事更新が終えたら、有効化していました。

RUBYOPT=-W:deprecated

ruby2.7がEOLになったら、デフォルト有効となる挙動に戻しても良いかもですね。

プロを目指す人のためのRuby入門 読了

cherry本、第二版読了。 初版も読んでいたのですが、第二版も読んでみました。 サンプルコードも書きながら楽しく読み進めれました。 最近RubyRails初めた人が2冊目、3冊目あたりに読むのが良いかなぁという印象を持ちました。

個人的には

第11章のパターンマッチングが追加されているのが非常によかったです。 とても勉強になりました。 パターンマッチングは使うこともありそうなので、ここで勉強できて良かったと思いました。

また、12章のRubyデバッグ技法を身につける、もRuby3.1で入ったdebug.gemにも触れられていて良いです。

あと、13章のRubyに関するその他のトピック、で今はTime使っておけばよいということや、 警告表示の「RUBYOPT=-W:deprecated」にも触れられていてとても良いです。

ちなみに、環境変数以外での設定は知りませんでした。

Warning[:deprecated] = true