我有一个 Source 模型和 ArticlesController。当用户点击抓取按钮时,控制被传递到下面提到的 ArticlesController#Scrape
。然后,Scrape 调用 Source 模型,在该模型中,源被初始化,文章列表以散列形式返回到 Scrape
内的 articles
。
源模型 -
class Source
attr_accessor :source_name, :source_url, :source_type, :source_key, :tag_name
def self.all_instances
@@array
end
# Default constructor
def initialize
end
def initialize(source_name:, source_url:, source_type:, source_key:, tag_name:)
@source_name = source_name
@source_url = source_url
@source_type = source_type
@source_key = source_key
@tag_name = tag_name
@@array << self
end
def init
self.new('The Age',
'http://www.theage.com.au/rssheadlines/victoria/article/rss.xml',
'RSS',
'',
'Victoria News')
end
def import
init()
//returns hash of articles back
end
end
class ArticlesController < ApplicationController
def scrape
@get_Articles = Source.new
articles = @get_Articles.import
//stores articles in article model
//redirect to article path
end
end
我在 @get_Articles = Source.new
上的 ArticlesController#scrape
中收到 ArgumentError
在 Source 类中,正在调用构造函数 def initialize(source_name:, source_url:, source_type:, source_key:, tag_name:)
。为了纠正这个问题,我还创建了一个默认构造函数,这样就不会调用参数化构造函数。但是,我不确定如何解决此问题。有人可以帮忙吗?
最佳答案
我认为您在使用 def initialize
方法时做错了。您不希望参数化构造函数只是将其删除。
如果你也想要这个,那么你也需要为空值处理这个。
仅仅创建默认构造函数并不能解决问题,因为它会被其他构造函数覆盖。
你可以这样试试
def initialize(options ={})
@source_name = options[:source_name] if options[:source_name].present?
#handle and assign other keys and values similer to this
@@array << self
end
现在你可以把它当作
@get_Articles = Source.new
或
@get_Articles = Source.new(source_name: "abc")
关于ruby-on-rails - 初始化构造函数时缺少关键字错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599166/