How to get class' filepath from methods in included mixin?

Hi,

File.dirname(__FILE__) returns the current folder where the script in,
How to get it from methods in included modules?

My sample code as below:

helper.rb

···

---------

module Helper
  def your_path
    puts instance_eval { File.expand_path(File.dirname(__FILE__)) } #
doesn't work
  end
end

a.rb
-----
require 'helper/helper'

class A
include Helper
end

A.new.your_path #=> return helper's file path, not class A's
--
Posted via http://www.ruby-forum.com/.

Nigel Hennan wrote:

Hi,

File.dirname(__FILE__) returns the current folder where the script in,
How to get it from methods in included modules?

My sample code as below:

helper.rb
---------

module Helper
  def your_path
    puts instance_eval { File.expand_path(File.dirname(__FILE__)) } #
doesn't work
  end
end

a.rb
-----
require 'helper/helper'

class A
include Helper
end

A.new.your_path #=> return helper's file path, not class A's

This seems to work:

[~/tmp] cat helper/helper.rb
module Helper
   def self.included m
     file = caller[1][/(.*):\d+$/, 1] ## a bit fragile, maybe
     dir = File.expand_path(File.dirname(file))
     m.const_set "YourPath", dir
   end

   def your_path
     self.class::YourPath
   end
end
[~/tmp] cat a.rb
require 'helper/helper'

class A
  include Helper
end

p A.new.your_path
[~/tmp] ruby a.rb
"/home/vjoel/tmp"

···

--
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Joel VanderWerf wrote:

This seems to work:

Yes, Thanks Joel!

Nigel

···

--
Posted via http://www.ruby-forum.com/.