Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > How to get class' filepath from methods in included mixin?

Reply
Thread Tools

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

 
 
Nigel Hennan
Guest
Posts: n/a
 
      05-07-2009
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/.

 
Reply With Quote
 
 
 
 
Joel VanderWerf
Guest
Posts: n/a
 
      05-07-2009
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

 
Reply With Quote
 
 
 
 
Nigel Hennan
Guest
Posts: n/a
 
      05-07-2009

Joel VanderWerf wrote:
> This seems to work:


Yes, Thanks Joel!

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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
Is there a way to find the class methods of a class, just like'methods' finds the instance methods? Kenneth McDonald Ruby 5 09-26-2008 03:09 PM
Reposting question - How to pull filepath from SQL to use in slide =?Utf-8?B?UnVkeQ==?= ASP .Net 0 05-11-2005 03:48 PM
Filepath lookup from id Andreas Zita ASP .Net 2 02-28-2005 01:38 PM
current filepath? Lauchlan M ASP .Net 1 08-18-2003 12:04 AM



Advertisments