Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
901 views
in Technique[技术] by (71.8m points)

ruby on rails - How to include all lib folder?

I want to extend core Array class with simple method:

class Array
  def to_hash
    result = Hash.new
    self.each { |a| result[a] = '' }
    result
  end
end

I put array.rb into lib/core_ext and tried to require it in application.rb by

config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

But still get undefined method 'to_hash' for ["var1", "var2", "var3"]:Array if tried to use it in model method. Of course I rebooted the server after code changes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Once way you can do this is by adding the following to one of the files in config/initializers

require 'core_ext/array`

All your autoload_paths config value does is make the paths available for when the classes/files are requested. In my app I might have some file structure as follows

- lib/
  |
  |- deefour.rb
  |- deefour/
     |
     |- core_ext.rb

In my deefour.rb I have

require 'deefour/core_ext'

and inside config/initializers I have a deefour.rb file containing simply

require 'deefour'

The only way the autoload config value you set will cause Rails to look auto load lib/deefour/core_ext.rb is if you had some call to a class Deefour::CoreExt that existed in that file. This is why my require 'deefour' line in the initializer knows to autoload the lib/deefour.rb file.

The explicit require 'deefour/core_ext' in lib/deefour.rb serves the same purpose, since it too does not follow the standard class-name-to-directory mapping Ruby/Rails will expect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...