2014-10-30 129 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 
相關問題