memo.log

技術情報の雑なメモ

【ソースコードリーディングメモ】irb で入力を受け付けているところと、実行しているところ

--nomultiline オプションで確認。この場合は、例えば以下で入力を受け付けていた。 reline ライブラリの readline メソッドで受け付け待機。

github.com

文字列を受け取るので、 eval メソッドでRubyコードに変換して実行。

github.com

【Ruby】MicroCMSで記事を全件取得するスニペット

# return [Array<OpenStruct>]
def all_contents
  limit = 10
  offset_number = 0
  contents = []

  loop do
    result = MicroCMS.list(
                "[MUST EDIT]",
                {
                  offset: offset_number,
                  limit: limit,
                }
              )

    total_count = result.total_count
    contents << result.contents

    if total_count >= offset_number + 1
      offset_number += limit
    else
      break
    end
  end

  contents.flatten
end

【Ruby】モジュールで定義されたメソッドをクラスメソッドにするときのメモ

require 'active_record'

module Test1
  def hoge
    "hoge1"
  end
end

module Test2
  def hoge
    "hoge2"
  end
end

module Test3
  extend ActiveSupport::Concern

  module ClassMethods
    def hoge3
      "hoge3"
    end
  end
end

class Test
  extend Test1
  extend Test2 # 後ろで定義されたモジュールが使われる
  include Test3
end

pp Test.hoge # => "hoge2"
pp Test.method(:hoge).source_location # ["test.rb", 8]
pp Test.hoge3

................

require 'active_record'

module M1
  extend ActiveSupport::Concern

  def config(key:)
    # この変数は include したクラスで参照可能
    @key = key
  end

  def instance_test1
    "instance_test"
  end

  module ClassMethods
    def class_test1
      "class_test1"
    end
  end
end

module M2
  def class_test2
    "class_test2"
  end
end

class Test
  include M1
  extend M2
end


pp Test.new.instance_test1 # "instance_test"
pp Test.class_test1 # "class_test"
pp Test.class_test2 # "class_test"

ActiveRecord単体でSQLiteを使うメモ

確認環境

amzn2.x86_64 
ruby 3.1.4p223 (2023-03-30 revision 957bb7cb81) [x86_64-linux]
activerecord (7.0.5)
sqlite3 (1.6.3-x86_64-linux)
名前                : sqlite
アーキテクチャー    : i686
バージョン          : 3.7.17

インストール

SQLite

 % sudo yum install sqlite  

Ruby

 % cat Gemfile                                                                                                                               (git)-[main] 
# frozen_string_literal: true

source "https://rubygems.org"

gem "activerecord"
gem "sqlite3"

データベースの準備

% sqlite3 testdb 
sqlite> create table users(id integer, name text);
sqlite> insert into user values(1, 'a');
sqlite> insert into user values(2, 'b');

Rubyのコード

require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter:   'sqlite3',
  database:  'testdb'
)

class User < ActiveRecord::Base
end

pp User.all

実行

 % be ruby active_record_test.rb
[#<User:0x00007f2f0e4ef2e8 id: 1, name: "a">, #<User:0x00007f2f0d90ed98 id: 2, name: "b">]