16
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

irbのshow_sourceが便利すぎた

Last updated at Posted at 2023-06-14

irbの機能が色々増えているということで、色々と試していたところ、show_sourceが便利すぎたのでまとめました。

show_sourceについて

引数でメソッドや定数を受け、そのソースコードを表示するコマンドです。
$でも同義です。

つまり、irbで show_source set_user$ set_userを実行すると、set_userメソッドの定義を確認することができます。

show_sourceのソースコードを見ながら、コマンドの実行を試してみました。

サンプルコード

irb> whereami

    1: class User < ApplicationRecord
    2:   validates :name, presence: true, uniqueness: true
    3:   validates :admin, inclusion: { in: [true, false] }
    4: 
    5:   def hoge
 => 6:     binding.irb
    7:   end
    8: end

以下の3種類の実行方法があります。

1. 「(Const)::(Name)」

irb> $ ActiveRecord::Base
実行結果

From: /Users/kyntk/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activerecord-7.0.5/lib/active_record/base.rb:282

  class Base
    extend ActiveModel::Naming

    extend ActiveSupport::Benchmarkable
    extend ActiveSupport::DescendantsTracker

    extend ConnectionHandling
    extend QueryCache::ClassMethods

... (一部省略しています)

    include SecureToken
    include SignedId
    include Suppressor
    include Encryption::EncryptableRecord
  end

2. 「(Class)#(method)」

irb> $ Article#user
実行結果
From: /Users/kyntk/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activerecord-7.0.5/lib/active_record/associations/builder/association.rb:103

        def #{name}
          association(:#{name}).reader
        end
      CODE

3. 「(method)」, 「(receiver).(method)」, 「(receiver)::(method)」

irb> $ admin?
irb> $ self.admin?
irb> $ self::admin?
実行結果
From: /Users/kyntk/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activemodel-7.0.5/lib/active_model/attribute_methods.rb:271

        ActiveSupport::CodeGenerator.batch(generated_attribute_methods, __FILE__, __LINE__) do |owner|
          attr_names.flatten.each { |attr_name| define_attribute_method(attr_name, _owner: owner) }
        end

感想

どこでメソッドが定義されているのかがわからないときに、メソッドからそのソースコードを確認できるのはとても便利だなと思いました。
ファイルと行数も表示されており、そのファイルも確認できるのも更に便利です。

16
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?