ruby 模块是否可以获取定义包含该模块的类的文件的目录?
我有一个模块和一个包含该模块的类。这些不是在同一文件或同一文件夹中定义的。我希望模块获取定义该类的目录。
# ./modules/foo.rb
module Foo
def self.included(obj)
obj_dirname = # ??? what goes here?
puts "the class that included Foo was defined in this directory: #{obj_dirname}"
end
end
# ./bar.rb
class Bar
include Foo
end
我希望它的输出是:
the class that included Foo was defined in this directory: ../
这可能吗?如果是这样,怎么办?
i've got a module and a class that includes the module. these are not defined in the same file, or in the same folder. i want the module to get the directory that the class is defined in.
# ./modules/foo.rb
module Foo
def self.included(obj)
obj_dirname = # ??? what goes here?
puts "the class that included Foo was defined in this directory: #{obj_dirname}"
end
end
# ./bar.rb
class Bar
include Foo
end
i would expect the output of this to be:
the class that included Foo was defined in this directory: ../
is this possible? if so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
类可以在许多文件中定义,因此您的问题没有真正的答案。另一方面,您可以知道
include Foo
是从哪个文件中创建的:这将是您要查找的路径,除非有
MyClass.send :include, Foo
code> 定义 MyClass 的其他地方...注意:对于 Ruby 1.8.6,
需要 'backports'
或将partition
更改为其他的东西。Classes can be defined in many files, so there is no real answer to your question. On the other hand, you can tell from which file the
include Foo
was made:This will be the path you're looking for, unless there's a
MyClass.send :include, Foo
somewhere else then where MyClass was defined...Note: For Ruby 1.8.6,
require 'backports'
or change thepartition
to something else.没有内置的方法可以找出模块或类的定义位置(据我所知)。在 Ruby 中,您可以随时随地重新打开模块/类并添加或更改行为。这意味着,通常没有一个地方可以定义模块/类,并且这样的方法没有意义。
然而,在您的应用程序中,您可以遵循某些约定,以便能够构造源文件名。例如,在 Rails 中,页面控制器按照约定命名为 PagesController,主要在文件 app/controllers/pages_controller.rb 中定义。
There's no built-in way to find out where a module or class was defined (afaik). In Ruby, you can re-open a module/class at any time and any place and add or change behavior. This means, there's usually no single place where a module/class gets defined and such a method wouldn't make sense.
In your application, you can however stick to some convention so that you are able to construct the source filename. E.g. in Rails, a pages controller is by convention named PagesController and gets defined primarily in the file app/controllers/pages_controller.rb.
这是你想要的吗?
编辑:根据评论进行更改。
Does this do what you want?
Edit: changed according to comments.