I have the following file hierarchy:
Lib > MyModule.rb
Lib > MyModule.rb > MyClass.rb
In MyModule.rb, I have an initialize method:
def initialize(variable, parameter)
@variable = variable
@parameter = parameter
end
However, when I try and create an instance of my class, the result is an error:
undefined method: set is not defined for nil
I tried to fix it with this reconstructed version of initialize:
def initialize(variable, parameter)
@variable = variable
@parameter = parameter
end
This alleviates the error that I received. However, now I go to create an instance of my class in an HTML.erb file:
<%= MyModule::MyClass.new("string", 1) %>
Here I get an argument error: 2 for 0
Can anyone explain this?
More information as requested:
I’m trying to create a few methods that create html tags as convenience wrappers for commonly used elements. In particular, these utilize the content_tag helper method of rails to create new methods. The plan is eventually to add in nested tag support by using the simple << operator.
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
Now this is the lowest level of the module; these are going to be common to all of the tags that I will be implementing. I then have a class in the Tags folder (Lib/tags/div.rb):
module Tags
class DivTag
def initialize(content, options, &block)
super(:div, content, options, &block)
end
end
end
Then in my test file main.rb (which is what is routed to when going to localhost)
And this is where I get my error.
“def Tags” – this is wrong approach, you should use
class Tags …
To call “super” in method – class should be inherited from other class, for example
class DivTag < Tags::Base
def initialize
super() # <- Tags::Base#initialize
end
end
by default every new class inheriting from “Object” class, and Object#initialize accept 0 arguments.
Why you don’t use “content_tag” helper (http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag) ? Its almost what you want