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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Nigel H. (Guest)
on 2009-05-07 04:16
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
Joel VanderWerf (Guest)
on 2009-05-07 04:41
(Received via mailing list)
Nigel Hennan wrote:
> module 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"
Nigel H. (Guest)
on 2009-05-07 05:08
Joel VanderWerf wrote:
> This seems to work:

Yes, Thanks Joel!

Nigel
This topic is locked and can not be replied to.