【问题标题】:How to avoid using instance variables in modules?如何避免在模块中使用实例变量?
【发布时间】:2017-01-03 02:29:39
【问题描述】:

我正在勾勒 CsvVerify 模块的工作原理。有没有办法不污染将包含带有实例变量的模块的类

Idea 的灵感来自 virtus,如下所示:

employee_csv_importer.rb(使用模块)

class EmployeeCsvImporter
  include CsvVerify

  headers 'ID', 'First Name', 'Last Name', 'Title or Department',
    'Age', 'Native Language', 'Fluent in English?'
end

csv_verify.rb

module CsvVerify
  puts "included"

  def headers(*names)
    @config = Config.new
  end
end

config.rb

module CsvVerify
  class Config

  end
end

那么我该如何重新组织它以避免@config 污染EmployeeCsvImporter?

PS。 为什么现在这甚至不起作用?
为什么我从运行 employee_csv_importer.rb 得到这个输出?

included
/data/gems/csv_verify/examples/1_employees.rb:6:in `<class:EmployeeCsvImporter>':
undefined method `headers' for EmployeeCsvImporter:Class (NoMethodError)

【问题讨论】:

    标签: ruby module architecture instance-variables


    【解决方案1】:

    我建议您首先在没有moduleinclude 的情况下开始编写您的功能。这有助于塑造结构,特别是如果您是 Ruby 新手。

    通过包含CsvVerify 添加的方法是作为实例方法添加的,而不是类方法。因此你有这个NoMethodError

    【讨论】:

    • def self.headers 也不起作用。所以你建议我让 CsvVerify 成为一个类并让 EmployeeCsvImporter 继承它?此外,我对 ruby​​ 并不陌生,但对编写模块很感兴趣。从未在其他语言中找到类似的概念,总有一天必须掌握它。
    • 您需要使用提供header 方法的模块扩展您的类。我建议您首先写出您的课程的全部功能,然后决定如何以及是否想要/需要将其拆分为模块。 .
    • ok 扩展工作,谢谢,但这意味着@config 将是一个类变量?
    • 是的。您正在EmployeeCsvImporter 中从类级别配置标头。如前所述:我首先将整个功能编写在一个类中以使其正常工作。然后通过提取使其可重复使用。特别是如果你是新手。
    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 2011-10-03
    • 2015-04-15
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多