tags:

views:

53

answers:

2

Hello guys,

I'm developing two Ruby gems, one is a framework, the other is an application. My main app's class inherits from a framework's class.

The class defined in the framework have some file loading methods that rely on __FILE__ so subclasses can load resources relative to their path.

What I want is for the subclasses to be able to use those methods defined in the parent without (basically) touching them. Is it possible?

The problem is with __FILE__, it doesn't change if the code is called from a subclass, so the loading resource methods are "stuck" in the frameworks directory, instead of trying to load from the app dirs.

I know I can redefine those methods in the subclass, but I wanted to take advantage of them being already defined in the parent.

I want the subclasses to refer to their own directory (where the subclass file is) using a method defined in the parent, that's the problem.

Or do I have to set the app directory by hand?


I'll try to make that clearer:

Is it possible to write a method like this:

# /home/usr/framework/parent.rb
class Parent
  def show_my_path
    puts File.dirname(__FILE__)
  end
end

# /home/usr/app/app.rb
# require Parent
class App < Parent
end
App.new.show_my_path
# Can we have here /home/usr/app
# instead of /home/usr/framework ?
# What's the right way to do this?
A: 

__FILE__ is transform during the code read. So it can't be change. Even in a proc.

You can try to extract information with caller method maybe.

shingara
Yeah, now I can see that, so probably the best way to do it is like Webbisshh said.Even if I do access the `caller`, there is no way to get the dir unless the client app pass the `__FILE__` around explicitly, I think.
lobo_tuerto
+1  A: 

As We know that __FILE__ will have current file name whatever it is. so you can try this -

# /home/usr/framework/parent.rb
class Parent
  def show_my_path(filename)
    puts File.dirname(filename)
  end
end

# /home/usr/app/app.rb
# require Parent
class App < Parent
end
App.new.show_my_path(__FILE__)

What say?

Webbisshh
Yeah that was the way I had to go, and the way I wanted to avoid.I hoped there would be a way around it. :(
lobo_tuerto
Ya actually that was the most simple way i could think of!
Webbisshh