Ruby on rails 从MVC模式之外的类调用rails方法
我正在创建一个新闻提要应用程序,它使用XML提要供以后使用 我正在努力让应用程序调用我在默认Rails文件夹之外的类中编写的方法。如何将此类加载到应用程序中以在控制器中使用(例如)?我已经读了一大堆关于SO的问题,得到了下面的结构/代码 我的理解是,对于以下内容,我不需要Ruby on rails 从MVC模式之外的类调用rails方法,ruby-on-rails,Ruby On Rails,我正在创建一个新闻提要应用程序,它使用XML提要供以后使用 我正在努力让应用程序调用我在默认Rails文件夹之外的类中编写的方法。如何将此类加载到应用程序中以在控制器中使用(例如)?我已经读了一大堆关于SO的问题,得到了下面的结构/代码 我的理解是,对于以下内容,我不需要要求从控制器中“fetch_feed.rb”,也不需要在lib文件夹中放置任何内容。但是,我得到以下错误: NoMethodError (undefined method `fetch_news' for FetchFeed:C
要求从控制器中“fetch_feed.rb”
,也不需要在lib文件夹中放置任何内容。但是,我得到以下错误:
NoMethodError (undefined method `fetch_news' for FetchFeed:Class):
app/controllers/v1/news\u items\u controller.rb:18:in'index'
我试图从FetchFeed
类调用一个方法
文件夹结构
- app
- controllers
- retrievers
- fetch_feed.rb
fetch_feed.rb
class FetchFeed
def fetch_news
// Code here
end
end
module FeedReaderApi
class Application < Rails::Application
config.autoload_paths += %W(#{Rails.root}/app/retrievers)
// Other code
end
end
class V1::NewsItemsController < ApplicationController
def index
FetchFeed.fetch_news
end
end
应用程序.rb
class FetchFeed
def fetch_news
// Code here
end
end
module FeedReaderApi
class Application < Rails::Application
config.autoload_paths += %W(#{Rails.root}/app/retrievers)
// Other code
end
end
class V1::NewsItemsController < ApplicationController
def index
FetchFeed.fetch_news
end
end
模块FeedReaderApi
类应用程序
news\u item\u controller.rb
class FetchFeed
def fetch_news
// Code here
end
end
module FeedReaderApi
class Application < Rails::Application
config.autoload_paths += %W(#{Rails.root}/app/retrievers)
// Other code
end
end
class V1::NewsItemsController < ApplicationController
def index
FetchFeed.fetch_news
end
end
ClassV1::NewsItemsController
非常感谢您的帮助。应该是:
FetchFeed.new.fetch_news
fetch\u news
已定义为实例方法。因此,您需要一个FetchFeed
实例来调用fetch\u news
方法
要使FetchFeed.fetch_news
工作,请将其定义为类方法,如下所示:
class FetchFeed
def self.fetch_news
// Code here
end
end
或
类FetchFeed
等级应为:
FetchFeed.new.fetch_news
fetch\u news
已定义为实例方法。因此,您需要一个FetchFeed
实例来调用fetch\u news
方法
要使FetchFeed.fetch_news
工作,请将其定义为类方法,如下所示:
class FetchFeed
def self.fetch_news
// Code here
end
end
或
类FetchFeed
课堂完美。在我有机会跟进之前,你已经更新了答案。你通灵吗?@tonyedwardspz还没有:)哈哈。不管怎样,谢谢,计时器用完了我就接受。但你已经知道了……完美。在我有机会跟进之前,你已经更新了答案。你通灵吗?@tonyedwardspz还没有:)哈哈。不管怎样,谢谢,计时器用完了我就接受。但你已经知道。。。。。。