Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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
azusanakano
中野システム研究所、所長(仮) 東京四念処禅道場、師範(仮)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした