helper class to extract localized files

arnaud sellenet committed Jun 03, 2014
commit e0caa29026b2824dd63c84ac61959869e5e4656f
Showing 2 changed files with 66 additions and 0 deletions
locomotive/steam/loaders/yml/utils/localized_tree.rb b/lib/locomotive/steam/loaders/yml/utils/localized_tree.rb +33 -0
@@ @@ -0,0 +1,33 @@
+ module Locomotive
+ module Steam
+ module Utils
+ class LocalizedTree
+
+ def initialize(entries, extensions)
+ @entries = entries
+ @extensions = extensions
+ end
+
+ def to_hash
+ group_by(locale_regexp)
+ end
+
+
+ private
+
+ def group_by(regexp)
+ @entries.each_with_object({}) do |entry, hsh|
+ file, key, subkey, *_ = regexp.match(entry).to_a
+ next unless file
+ (hsh[key] ||= {})[subkey.try(:to_sym) || :default] = file
+ end
+ end
+
+ def locale_regexp
+ /\A(.+?)(?:\.(.{2})){0,1}\.(?:(#{@extensions.join('|')})\.*)+\Z/
+ end
+
+ end
+ end
+ end
+ end
spec/unit/loaders/utils/localized_tree_spec.rb +33 -0
@@ @@ -0,0 +1,33 @@
+ require 'spec_helper'
+
+ describe Locomotive::Steam::Utils::LocalizedTree do
+
+ describe '#to_hash' do
+ let(:tree) { [ 'a.fr.haml', 'a.haml', 'b.xml', 'b.fr.haml', 'z.txt' ] }
+ let(:extensions) { ['haml','xml'] }
+ subject { Locomotive::Steam::Utils::LocalizedTree.new(tree, extensions).to_hash }
+
+
+ it { should be_kind_of Hash }
+
+ it 'has root as key' do
+ subject.keys.should eq ['a', 'b']
+ end
+
+ it { should eql ({
+ 'a' => {fr: 'a.fr.haml', default: 'a.haml'},
+ 'b' => {default: 'b.xml', fr: 'b.fr.haml'}
+ })
+ }
+
+ context 'multiple extensions' do
+ let(:tree) { [ 'a.fr.haml.xml', 'a.haml', 'b.xml.haml', 'b.fr.haml'] }
+ it { should eql ({
+ 'a' => {fr: 'a.fr.haml.xml', default: 'a.haml'},
+ 'b' => {default: 'b.xml.haml', fr: 'b.fr.haml'}
+ })
+ }
+
+ end
+ end
+ end