Tbpgr Blog

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

Ruby | Kernel | autoload

概要

Kernel#autoload(const_name, feature)

詳細

定数 const_name を最初に参照した時に feature を Kernel.#require するように設定します。

サンプルコード

loaded.rb

class Loaded
  def loaded
    "loaded"
  end
end

kernel_autoload.rb

# encoding: utf-8
require 'tbpgr_utils'

autoload :Loaded, './loaded'

bulk_puts_eval binding, <<-EOS
autoload? :Loaded
Loaded.new.loaded
autoload? :Loaded
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils
出力
autoload? :Loaded # => "./loaded"
Loaded.new.loaded # => "loaded"
autoload? :Loaded # => nil