我想设计一个类如下:
class A
@@instances ||= []
attr_reader :path, :name
def initialize name
@name = name
@path = # I don't know how to get the path of instance.
@@instances << self
end
def self.show_all_instances
puts @@instances.collect {|i| "Name: #{i.name}, Path: #{i.path}"} .join('\n')
end
end
然后我将在不同的文件夹下创建许多实例。
folder1/foo.rb
A.new 'foo'
folder2/bar.rb
A.new 'bar'
...
我希望结果如下
A.show_all_instances
输出:
Name: foo, Path: folder1/foo.rb
Name: bar, Path: folder2/bar.rb
...
那么如何知道调用类的位置,输入路径?
抱歉,我不能很好地解释我的问题。我想获得实例创建的ruby文件路径...
答案 0 :(得分:3)
#a.rb
def initialize name,path
@name = name
@path = path
@@instances << self
end
#foo.rb
a = A.new 'foo',__FILE__ #or File.expand_path __FILE__
答案 1 :(得分:0)
我不确定“文件夹下的实例”是什么意思。假设它是实例“make”的文件,并且文件名始终是“instance_name.rb”,并使用gem install y_support
来处理对象命名和实例管理的平凡事务,解决方案是:< / p>
require 'y_support/name_magic'
class A
include NameMagic
attr_reader :path
def initialize
@path = File.dirname( File.expand_path __FILE__ )
end
def inspect
"Name: '#{name}', path '#{path}/#{name.to_s.downcase}.rb'"
end
end
# Now in folder1
Foo = A.new
# and in folder2
Bar = A.new
# Then:
A.instances
#=> [Name: 'Foo', path 'folder1/foo.rb', Name: 'Bar', path 'folder2/bar.rb']