ruby-on-rails - 初始化构造函数时缺少关键字错误

标签 ruby-on-rails ruby oop

我有一个 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/

相关文章:

ruby-on-rails - 如何在 rails3 中创建动态路由和助手

java - 内部类。它的目的是什么?

python - 是否可以在 python 中的函数上使用模式匹配?就像一个可以响应多个调用的函数

c++ - 实心: Does DIP mean that composition/aggreation to an object is forbidden?

ruby-on-rails - 是否可以将 tinyMCE 与 rails_admin 一起使用?

ruby - 安装 gem 失败并出现权限错误

ruby-on-rails - 我无法引导 Spork 配置

ruby-on-rails - 音频标签在 Active admin、Ruby on Rails 中不起作用

ruby-on-rails - 在 MAC OS 10.9 Mavericks(测试版)上安装 RAILS

Ruby 类初始化