Class: Tins::Find::Finder

Inherits:
Object show all
Defined in:
lib/tins/find.rb

Defined Under Namespace

Modules: PathExtension

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Finder

Returns a new instance of Finder.



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/tins/find.rb', line 57

def initialize(opts = {})
  @show_hidden     = opts.fetch(:show_hidden)     { true }
  @raise_errors    = opts.fetch(:raise_errors)    { false }
  @follow_symlinks = opts.fetch(:follow_symlinks) { true }
  if opts.key?(:visit) && opts.key?(:suffix)
    raise ArgumentError, 'either use visit or suffix argument'
  elsif opts.key?(:visit)
    @visit = opts.fetch(:visit) { -> path { true } }
  elsif opts.key?(:suffix)
    @suffix = Array(opts[:suffix])
    @visit = -> path { @suffix.nil? || @suffix.empty? || @suffix.include?(path.suffix) }
  end
end

Instance Attribute Details

Returns the value of attribute follow_symlinks.



75
76
77
# File 'lib/tins/find.rb', line 75

def follow_symlinks
  @follow_symlinks
end

#raise_errorsObject

Returns the value of attribute raise_errors.



73
74
75
# File 'lib/tins/find.rb', line 73

def raise_errors
  @raise_errors
end

#show_hiddenObject

Returns the value of attribute show_hidden.



71
72
73
# File 'lib/tins/find.rb', line 71

def show_hidden
  @show_hidden
end

#suffixObject

Returns the value of attribute suffix.



77
78
79
# File 'lib/tins/find.rb', line 77

def suffix
  @suffix
end

Instance Method Details

#find(*paths) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/tins/find.rb', line 87

def find(*paths)
  block_given? or return enum_for(__method__, *paths)
  paths.collect! { |d| d.dup }
  while path = paths.shift
    path = prepare_path(path)
    catch(:prune) do
      stat = path.finder_stat or next
      visit_path?(path) and yield path
      if stat.directory?
        ps = protect_from_errors { Dir.entries(path) } or next
        ps.sort!
        ps.reverse_each do |p|
          next if p == "." or p == ".."
          next if !@show_hidden && p.start_with?('.')
          p = File.join(path, p)
          paths.unshift p
        end
      end
    end
  end
end

#prepare_path(path) ⇒ Object



109
110
111
112
113
114
# File 'lib/tins/find.rb', line 109

def prepare_path(path)
  path = path.dup
  path.extend PathExtension
  path.finder = self
  path
end

#protect_from_errors(errors = Find::EXPECTED_STANDARD_ERRORS) ⇒ Object



116
117
118
119
120
121
# File 'lib/tins/find.rb', line 116

def protect_from_errors(errors = Find::EXPECTED_STANDARD_ERRORS)
  yield
rescue errors
  raise_errors and raise
  return
end

#visit_path?(path) ⇒ Boolean

Returns:

  • (Boolean)


79
80
81
82
83
84
85
# File 'lib/tins/find.rb', line 79

def visit_path?(path)
  if !defined?(@visit) || @visit.nil?
    true
  else
    @visit.(path)
  end
end