4

I'm trying to figure out where a module is extended from in Ruby. Right now the only thing I've been able to come up with is to use caller and pick out the appropriate line. Is there a more idiomatic and less brittle way to handle it?

module ClassMethods
  def self.extended(base)
    p caller[2]
  end
end
6
  • Do you just want to find the name of the file? or do you want to find the specific line number too? Nov 14, 2016 at 1:50
  • I'm just looking for the path to the file. Not concerned about the line number.
    – lobati
    Nov 14, 2016 at 1:59
  • 2
    Are you just curious, like for diagnostic purposes? Using this kind of thing in actual code could be problematic.
    – tadman
    Nov 14, 2016 at 2:09
  • Well, I'm using it in actual code, though it won't be something I lean on too heavily. I'm trying to automatically load a config file inside a project if it's there. If not, no worries.
    – lobati
    Nov 14, 2016 at 2:29
  • 1
    That's going to be very confusing for people. It might be better to let people specify the location directly.
    – tadman
    Nov 14, 2016 at 3:00

1 Answer 1

2

I would personally go for something like this (based on OP's comment):

module ClassMethods
end

class Object
  def extend_with_path(mod, filename)
    p filename
    self.extend(mod)
  end
end


class Foo
  extend_with_path ClassMethods, __FILE__
end

Assuming you have internal knowledge of the base class, you could try something like this:

module ClassMethods
  def self.extended(base)
    p base.new.method(:superfluous_method).source_location
  end
end

class Foo
  def superfluous_method
  end

  extend ClassMethods
end

PS: I am aware this is a giant hack and not very nice, I would be curious to know if there are better ways of doing something like this.

3
  • 1
    Nice, though at that point I might as well have the path literally defined for the module instead: class Foo; FILE_PATH = __FILE__; extend ClassMethods; end.
    – lobati
    Nov 14, 2016 at 2:30
  • 1
    Thanks. If my approach ends up being too painful I'll probably end up swapping it out for something like that. github.com/mockdeep/configurator/commit/03f208
    – lobati
    Nov 14, 2016 at 3:18
  • Sorry, I deleted my earlier reply, it was "Yeah, very good point, in that case I would honestly prefer to pass in the filename rather than reaching for the constant." Nov 14, 2016 at 3:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.