LoginSignup
61
61

More than 5 years have passed since last update.

Ruby on Rails で lib ディレクトリの自作クラスを使用する

Last updated at Posted at 2015-04-23

Rails4 で lib ディレクトリの自作クラスを使用する

設定
config/application.rbにautoloadの設定を追加する。

config/application.rb
# to auto load lib/ directory
config.autoload_paths += %W(#{config.root}/lib)

これでlib ディレクトリ以下のファイルが、下記のディレクトリ・ファイル構成と命名の規約に従うと、自動的に読み込まれるようになります。

1.ファイル名は小文字
2.単語の区切りは'_'

1. lib/直下に置く場合

lib/foo_bar.rb
class FooBar
  def hello
    puts "FooBar: hello world"
  end
end

2. lib/foo/ディレクトリにファイルを置く場合

lib/foo/bar.rb
module Foo
  class Bar
    def hello
      puts "Foo::Bar: hello world"
    end
  end
end

2-2. lib/foo/ディレクトリに置く場合(moduleを使用しない)

lib/foo/bar.rb
class Foo::Bar
  def hello
    puts "Foo::Bar: hello world"
  end
end
61
61
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
61
61