Initialize doesn’t return a value; it’s called when the object is
instantiated (created). So the return value from open is disappearing
into thin air.
The “correct” way to do this is to use “super” to pass the appropriate
arguments to File#initialize, like so:
load CGI library (for CGI.escapeHTML)
require ‘cgi’
class HtmlReport < File
HEADER = ‘%s’
FOOTER = ‘’
def initialize(path)
# call File#initialize with the correct arguments
super(path, 'w')
end
def header(title)
# HTML-escape the report title
self.puts HEADER % CGI.escapeHTML(title)
end
def content(text)
self.puts text
end
def footer
self.puts FOOTER
close
end
end
[snipped]
if $0 == FILE
my_report = HtmlReport.new(‘test.html’)
my_report.header(‘Test report’)
my_report.content(‘Some text’)
my_report.footer
end
With the code I pasted above, running your test code produces a file
called test.html that looks like so:
def initialize(filename)
open(filename,‘w’) #Don’t know why this does not return a file object
end
It does return a file, but you don’t do anything with it… initialize
is not used to create an instance, but only to initialize de
attributes of an instance created by Ruby when you invoke
HtmlReport.new. So you’d have to assign the opened file to an instance
variable of your classe to avoid loosing the reference to it.
But the problem is deeper than that. I would not want to subclass
File. Subclassing is cool and very attractive when you first study OO,
but it’s not the right solution in many cases.
Cheers,
Luciano
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.