annotaterb commit log 流し読み

2025/3 ~ 2025/4で入ったコミットです。

Fix changelog_uri in gemspec #192

gemspec内のCHANGELOG.mdへのリンクで指定されているブランチがmasterからmainに修正されています。
masterの状態だと、RubyGem.org などで「変更履歴」から遷移した際にmaster -> main(デフォルトブランチ)のように余計なリダイレクトが走ってしまいます。

ref: Fix changelog_uri in gemspec #192

feat: add timestamp_columns config option #173

rails で migration した際に、追加されるtimestamp以外の類似カラム(destoryed_atなど)も timestamp として sort できるようにしています。

annotaterb ではファイルに表示するカラムの順序は以下のように決められています。

  • ID列
  • 通常の列(アルファベット順)
  • タイムスタンプ列
  • 関連付け列(アルファベット順)

ですが変更前は以下のように、created_at or updated_at のみがtimestampとして扱われ、仮に destroyed_at のようなカラムがあった際も timestamp として扱われませんでした。
なので destroyed_at のようなカラムも通常の列に組みこまれてしまいます。

# lib/annotate_rb/model_annotator/model_wrapper.rb
...
        cols.each do |c|
          if c.name.eql?("id")
            id = c
          elsif c.name.eql?("created_at") || c.name.eql?("updated_at")
            timestamps << c
          elsif c.name[-3, 3].eql?("_id")
            associations << c
          else
            rest_cols << c
          end
        end
        [rest_cols, timestamps, associations].each { |a| a.sort_by!(&:name) }

        ([id] << rest_cols << timestamps << associations).flatten.compact

なので、今回の変更ではtimestamp_columnsオプションに定義されたカラムであるならば、timestampとして扱われるようになっています。
例えばtimestamp_columnsオプションに[‘created_at’, ‘updated_at’, destroyed_at’]と設定して場合、設定した並び順でファイルに書き込まれることになります。

# lib/annotate_rb/model_annotator/model_wrapper.rb
      DEFAULT_TIMESTAMP_COLUMNS = %w[created_at updated_at]
       ...
        timestamp_columns = @options[:timestamp_columns] || DEFAULT_TIMESTAMP_COLUMNS
       ...
        cols.each do |c|
          if c.name.eql?("id")
            id = c
          elsif timestamp_columns.include?(c.name)
            timestamps << c
          elsif c.name[-3, 3].eql?("_id")
            associations << c
          else
            rest_cols << c
          end
        end

        timestamp_order = timestamp_columns.each_with_index.to_h
        timestamps.sort_by! { |col| timestamp_order[col.name] }
        [rest_cols, associations].each { |a| a.sort_by!(&:name) }

        ([id] << rest_cols << timestamps << associations).flatten.compact

ref: feat: add timestamp_columns config option #173

fix: Handle case when table_name_prefix specified as symbol #208

シンボルのprefixが付与されたテーブルからindexを抽出する際に、symbol -> Stringへの変更をするようにした修正になります。

以下のような実装だと、prefixがシンボルのケースで TypeErrorが起きてしまいます。

# lib/annotate_rb/model_annotator/model_wrapper.rb
...
table_name_without_prefix = table_name.to_s.sub(@klass.table_name_prefix, "")
...
irb> ':hoge_piyo'.sub(:hoge_, '')
`sub': wrong argument type Symbol (expected Regexp) (TypeError)

':hoge_piyo'.sub(:hoge_, '')

なのでこの変更では一度 to_s で String へ変更してから処理を行うようにしています。

# lib/annotate_rb/model_annotator/model_wrapper.rb
...
table_name_without_prefix = table_name.to_s.sub(@klass.table_name_prefix.to_s, "")
...

ref: fix: Handle case when table_name_prefix specified as symbol by gururuby · Pull Request #208 · drwl/annotaterb