[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

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

Nigel Hennan

5/7/2009 12:16:00 AM

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-....

2 Answers

Joel VanderWerf

5/7/2009 12:41:00 AM

0

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

Nigel Hennan

5/7/2009 1:08:00 AM

0


Joel VanderWerf wrote:
> This seems to work:

Yes, Thanks Joel!

Nigel
--
Posted via http://www.ruby-....