Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Module | autoload

概要

Module#autoload(const_name, feature) -> nil

詳細

定数 const_name を参照した際に feature の require を行う

サンプルコード

読み込み対象(./target.rb)

class Loaded
  def self.say
    "loaded!"
  end
end
require 'tbpgr_utils'

bulk_puts_eval binding, <<-EOS
autoload? :Loaded
autoload :Loaded, './target.rb'
autoload? :Loaded
Loaded.say
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

出力

autoload? :Loaded               # => nil
autoload :Loaded, './target.rb' # => nil
autoload? :Loaded               # => "./target.rb"
Loaded.say                      # => "loaded!"