Class: Tmsync::FileSearch

Inherits:
Object
  • Object
show all
Defined in:
lib/tmsync.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_path:, matching_regex:, exclude_regex:) ⇒ FileSearch

Initializes a file search object.



19
20
21
22
23
# File 'lib/tmsync.rb', line 19

def initialize(base_path:, matching_regex:, exclude_regex:)
  @base_path = base_path
  @matching_regex = /#{matching_regex}/
  @exclude_regex = /#{exclude_regex}/
end

Instance Method Details

#find_all_grouped_by_languageHash

Finds all files with corresponding language within a given directory matching the specified regexes.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/tmsync.rb', line 29

def find_all_grouped_by_language
  all_files = Dir.glob(File.join(@base_path, '**/*'))

  # apply exclude regex
  found_files = all_files.select { |file_path|
    file_path !~ @exclude_regex && !File.directory?(file_path)
  }

  # exclude empty files
  found_files = found_files.select { |file_path|
    content = File.open(file_path, 'r') { |f| f.read }
    !content.strip.empty?
  }

  # apply matching regex
  found_files = found_files.select { |file_path|
    file_path =~ @matching_regex
  }.map { |file_path|
    [file_path.match(@matching_regex).captures.last, file_path]
  }

  result = found_files.group_by(&:first).map { |k,v| [k, v.each(&:shift).flatten] }.to_h

  # replace nil key with fallback language
  if !(nil_values = result[nil]).nil?
    result[Tmsync::Constants::FALLBACK_LANGUAGE] = nil_values
    result.delete(nil)
  end

  result
end