gpt4 book ai didi

ruby-on-rails - 初始化 Ruby 模块

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:14 25 4
gpt4 key购买 nike

尝试学习 Ruby,下面是我为了测试 IO Ruby 功能而创建的模块。当我运行以下测试时:

    subject{TestGem.new}    

it 'should be_a Module' do
subject.is_a Module
end

it 'creates a config file' do
subject.init_config
File.open("program.config", "r") { |io| io.readline }.should eq "default_file.txt"
end

我都收到了这个错误:

 Failure/Error: subject{TestGem.new}
NoMethodError:
undefined method `new' for TestGem:Module

这是我正在测试的模块。任何帮助/建议将不胜感激:)

$LOAD_PATH.unshift File.expand_path("../test_gem", __FILE__)

require 'version'
require 'hello'

module TestGem

@default_file_name
@supported_types

def initialize
default_file_name = 'default_file.txt'
supported_types = ['txt', 'pdf']
end

puts "module TestGem defined"

def self.init_config
File.open('program.config', "w") do |f|
f.write(yaml(@default_file_name))
f.write(yaml(@supported_types))
end
end

class MyFile

def self.first(filename)
File.open(filename, "r") {|f| f.readline}
end

def self.last(filename)
File.open(filename, "r")[-1]
end
end

class MyError < StandardError
puts "Standard Error"
end
end

最佳答案

简答:你不能实例化模块对象

module A
end

class B
end

B.methods - A.methods #=> [:new, :superclass, :allocate]

要测试一个模块,你可以像这样将它包含在一个对象中

  object = Object.new
object.extend(TestGem)

或者如果您的模块依赖于某些类行为,您可以创建一些示例类。

关于ruby-on-rails - 初始化 Ruby 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15016288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com