我有以下文件层次结构:
Lib > MyModule.rb Lib > MyModule.rb > MyClass.rb
在MyModule.rb中,我有一个初始化方法:
def initialize(variable, parameter)
@variable = variable
@parameter = parameter
end但是,当我尝试创建类的实例时,结果是一个错误:
undefined method: set is not defined for nil我试着用initialize的这个重构版本来修复它:
def initialize(variable, parameter)
@variable = variable
@parameter = parameter
end这减轻了我收到的错误。但是,现在我要在HTML.erb文件中创建我的类的一个实例:
<%= MyModule::MyClass.new("string", 1) %>这里我得到了一个参数错误:2对应于0
有人能解释这个吗?
根据要求提供更多信息:
我正在尝试创建一些方法来创建html标记,作为常用元素的方便包装器。特别是,它们利用rails的content_tag辅助方法来创建新方法。我们的计划是最终通过使用简单的<<操作符来添加嵌套标签支持。
Lib/tags.rb
module Tags
include ActionView::Helpers::TagHelper
include ActionView::Helpers::JavaScriptHelper
include ActionView::Context
def initialize(type, content, options, &block)
@type = type
@content = content
@options = block_given? ? nil : options
@block = block_given? ? block : nil
end
def show
if @block.nil?
content_tag(@type, @content, @options)
else
content_tag(@type, @content, @options) { @block.call }
end
end
end现在这是模块的最低层;这些将是我将要实现的所有标记的公共级别。然后我在Tags文件夹(Lib/tags/div.rb)中有一个类:
module Tags
class DivTag
def initialize(content, options, &block)
super(:div, content, options, &block)
end
end
end然后在我的测试文件main.rb中(这是在转到本地主机时路由到的)
这就是我的错误所在。
发布于 2012-04-09 11:21:47
"def Tags“--这是错误的方法,你应该使用class标签...
要在方法类中调用“Tags::Base#initialize”-类应该继承自其他类,例如类DivTag < Tags::Base def initialize super() # <- Tags::Base#initialize end end
默认情况下,从"Object“类继承的每个新类和Object#initialize都接受0个参数。
为什么不使用"content_tag“helper (http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag)?这几乎就是你想要的
https://stackoverflow.com/questions/10068193
复制相似问题