2014-10-01 54 views
0

我在Rails 4.1上設置Grape。根據http://funonrails.com/2014/03/building-restful-api-using-grape-in-rails/,我把它放在lib裏面。爲什麼Rails自動加載失敗,文件在那裏?

我想放在分隔的文件的輔助方法,文件結構是類似以下內容:

lib 
|--- api 
    |--- root.rb 
    |--- helpers 
     |--- base_helper.rb 

而且裏面root.rb,API定義:

module API 
    class Root < Grape::API 
    formatter :json, Grape::Formatter::Jbuilder 

    helpers API::BaseHelper 
    end 
end 

base_helper.rb內容只是簡單的:

module API 
    module BaseHelper 
    def test 
     "I am a test helper" 
    end 
    end 
end 

當我啓動應用程序時,我ge t:

/Users/Larry/.rvm/gems/[email protected]/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:481:in `load_missing_constant': Unable to autoload constant BaseHelper, expected /Users/Larry/Gallows/jianshu.io/maleskine/lib/api/helpers/base_helper.rb to define it (LoadError) 

但是base_helper.rb實際上是在錯誤中提到的正確路徑。

如果我刪除helpers API::BaseHelper,autoload可以找到BaseHelper正確。

這是爲什麼?我做錯了什麼?

+0

lib/api/helpers/base_helper.rb文件的內容是什麼? – 2014-10-01 06:59:35

回答

1

調試成Rails源代碼後,我發現了這個問題。

首先,由於輔助文件helpers文件夾中,該文件應中Helpers模塊定義:

module API 
    module Helpers 
    module BaseHelper 
     def test 
     "I am a test helper" 
     end 
    end 
    end 
end 

其次,API::Helpers::BaseHelper具有路徑後綴api/helpers/base_helper,所以一定要確保"#{Rails.root}/lib/" is inside your autoload path. Then ActiveSupport`會發現它您。

0

確保您的BaseHelper位於API模塊內。應該這樣定義的:

module API 
    module BaseHelper 
    end 
end 
+0

是的,它在API裏面。我剛剛更新了主帖。 – larryzhao 2014-10-01 09:36:33

+1

我認爲這是因爲它在'助手'裏面。 – 2014-10-02 01:59:14

+0

是的,它只是問題所在。只需在那裏發佈答案。 – larryzhao 2014-10-02 09:39:54

0

嘗試改變

helpers API::BaseHelper 

helpers ::API::BaseHelper 

指定絕對你想要加載類。

+0

同樣的事情...不工作。 – larryzhao 2014-10-01 13:15:04