Class: Classifieds::Parser

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

Class Method Summary collapse

Class Method Details

.classifieds_ignore?(string) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/classifieds/parser.rb', line 49

def self.classifieds_ignore?(string)
  string.start_with?('!')
end

.detect_target(string) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/classifieds/parser.rb', line 29

def self.detect_target(string)
  path = string.match(/^!?(.+)/)[1]
  absolute_path = File.join(Dir.pwd, path)

  # Dir.glob notation
  if absolute_path.include?('*')
    recursive_glob(absolute_path)
  else
    case File.ftype(path)
    when 'file'
      absolute_path
    when 'directory'
      recursive_glob(File.join(absolute_path, '*'))
    else
      raise ParseError, "invalid file type: #{string}"
    end
  end
rescue Errno::ENOENT
end

.parse(text) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/classifieds/parser.rb', line 3

def self.parse(text)
  lines = text.each_line.map(&:chomp)
  result = lines.each_with_object([]) do |line, array|
    target = detect_target(line)

    case target
    when Array
      if classifieds_ignore?(line)
        target.each do |file|
          array.delete(file)
        end
      else
        array.concat(target)
      end
    when String
      if classifieds_ignore?(line)
        array.delete(target)
      else
        array << target
      end
    end
  end

  result
end

.recursive_glob(pattern) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/classifieds/parser.rb', line 53

def self.recursive_glob(pattern)
  Dir.glob(pattern).each_with_object([]) do |path, array|
    case File.ftype(path)
    when 'file'
      array << path
    when 'directory'
      array.concat(recursive_glob(File.join(path, '*')))
    end
  end
end