2014-10-30 131 views
1

我有几个灯具文件已定义,并且它们通过fixtures :all声明加载。

如何获取项目中所有灯具名称的数组?无需通过搜索* .yml文件的测试/夹具文件夹。获取项目中定义的所有灯具名称列表

P.S.一个明显的解决方案是定义这样的方法:

def all_fixtures 
    @all_fixtures ||= Dir.entries("#{Rails.root}/test/fixtures") 
         .select { |filename| /.*\.yml/.match(filename) } 
         .map{ |filename| filename[0..-5].to_sym } 
end 

但我确定有更优雅的东西。

回答

0

我不知道除了你提到的之外,还有其他方法。但是,您可以稍微清理一下这个语句。

直接从ActiveRecordfixutres.rb复制的逻辑,你可以做以下

def all_fixtures 
    # Get the fixture path that's configured 
    fixture_path = ActiveSupport::TestCase.fixture_path 
    # Get all YML files in all subdirectories 
    fixture_set_names = Dir["#{fixture_path}/{**,*}/*.{yml}"] 
    # Clip the name to get all the fixture names 
    fixture_set_names.map! { |f| f[(fixture_path.to_s.size + 1)..-5] } 
end 
相关问题