class ConfigStub < File
def initialize(location)
unless filename = location.gsub("/", “_”)
raise ArgumentError, INVALID_LOCATION_FORMAT
end @stub = File.open(CONFIG_PATH + filename, “w+”) # This might
need to
be more sophisticated depending on the rule
end # initialize
end # ConfigStub class
That is: your object is a subclass of File, and therefore an instance of
ConfigStub is a File. However you are also opening another File and
storing it in the instance variable @stub, and therefore it has a File
as well.
Choose one or the other. In my experience, delegation is the most
flexible and understandable approach, and although it needs some setting
up it ends up being simplest in the long run.
You can delegate manually:
class ConfigStub
def initialize(location) @stub = File.open(…)
end
def each(*args,&blk) @stub.each(*args,&blk)
end
def read(*args) @stub.read(*args)
end
… etc, and/or
def method_missing(*args,&blk) @stub.send(*args,&blk)
end
end
or use a wrapped up version of this - check out SimpleDelegator in
delegate.rb in the standard library.
If you want to subclass File, then you’ll need to ensure you call its
initialize method. Probably something like this (untested):
class ConfigStub < File
def initialize(location)
…
super(CONFIG_PATH + filename, “w+”) # in the superclass
end
end
But subclassing core classes can get you tied up in knots if you’re not
careful (as I think you’ve already discovered)