2015-09-15 18 views
1

我正在創建一個新聞饋送應用程序,該應用程序使用XML饋送供以後使用。從MVC模式以外的類中調用rails方法

我很努力讓應用程序調用我在默認Rails文件夾之外的類中寫入的方法。我如何將這個類加載到應用程序中以用於控制器(例如)?我已經閱讀了關於SO的一些問題,導致了以下結構/代碼。

我的理解是,以下我不需要從控制器require 'fetch_feed.rb'或任何東西放置在lib文件夾。但是我收到以下錯誤:

NoMethodError (undefined method `fetch_news' for FetchFeed:Class): 

應用程序/控制器/ V1/news_items_controller.rb:18:在'指數」

我試圖從FetchFeed類調​​用一個方法

文件夾結構

- app 
    - controllers 
    - retrievers 
     - fetch_feed.rb 

fetch_feed.rb

class FetchFeed 

    def fetch_news 
     // Code here 
    end 
end 

aplication.rb

module FeedReaderApi 
    class Application < Rails::Application 

    config.autoload_paths += %W(#{Rails.root}/app/retrievers) 
    // Other code 
    end 
end 

news_item_controller.rb

class V1::NewsItemsController < ApplicationController 

    def index 
    FetchFeed.fetch_news 
    end 

end 

任何幫助非常讚賞。

回答

4

應該是:

FetchFeed.new.fetch_news 

fetch_news已被定義爲一個實例方法。所以你需要一個FetchFeed的實例來調用fetch_news方法。

爲了FetchFeed.fetch_news工作,把它定義爲一個類的方法如下圖所示:

class FetchFeed 
    def self.fetch_news 
    // Code here 
    end 
end 

OR

class FetchFeed 
    class << self 
    def fetch_news 
    // Code here 
    end 
    end 
end 
+0

完美。在我有機會詢問後續行動之前,您已經更新了答案。你是否通靈? – tonyedwardspz

+1

@tonyedwardspz還沒有:) – emaillenin

+1

哈哈。無論如何,我會接受定時器用完時的情況。但是你已經知道了...... – tonyedwardspz