Class: Effective::CodeReader

Inherits:
Object
  • Object
show all
Defined in:
app/models/effective/code_reader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename, &block) ⇒ CodeReader

Returns a new instance of CodeReader.



5
6
7
8
# File 'app/models/effective/code_reader.rb', line 5

def initialize(filename, &block)
  @lines = File.open(filename).readlines
  block.call(self) if block_given?
end

Instance Attribute Details

#linesObject (readonly)

Returns the value of attribute lines.



3
4
5
# File 'app/models/effective/code_reader.rb', line 3

def lines
  @lines
end

Instance Method Details

#each_with_depth(from: nil, to: nil, &block) ⇒ Object

Iterate over the lines with a depth, and passed the stripped line to the passed block



11
12
13
14
15
16
17
18
19
20
21
22
# File 'app/models/effective/code_reader.rb', line 11

def each_with_depth(from: nil, to: nil, &block)
  Array(lines).each_with_index do |line, index|
    next if index < (from || 0)

    depth = line.length - line.lstrip.length
    block.call(line.strip, depth, index)

    break if to == index
  end

  nil
end

#first(from: nil, to: nil, &block) ⇒ Object Also known as: find

Returns the stripped contents of the line in which the passed block returns true



32
33
34
35
36
# File 'app/models/effective/code_reader.rb', line 32

def first(from: nil, to: nil, &block)
  each_with_depth(from: from, to: to) do |line, depth, index|
    return line if block.call(line, depth, index)
  end
end

#index(from: nil, to: nil, &block) ⇒ Object

Returns the index of the first line where the passed block returns true



25
26
27
28
29
# File 'app/models/effective/code_reader.rb', line 25

def index(from: nil, to: nil, &block)
  each_with_depth(from: from, to: to) do |line, depth, index|
    return index if block.call(line, depth, index)
  end
end

#last(from: nil, to: nil, &block) ⇒ Object

Returns the stripped contents of the last line where the passed block returns true



40
41
42
43
44
45
46
47
48
# File 'app/models/effective/code_reader.rb', line 40

def last(from: nil, to: nil, &block)
  retval = nil

  each_with_depth(from: from, to: nil) do |line, depth, index|
    retval = line if block.call(line, depth, index)
  end

  retval
end

#select(from: nil, to: nil, &block) ⇒ Object

Returns an array of stripped lines for each line where the passed block returns true



51
52
53
54
55
56
57
58
59
# File 'app/models/effective/code_reader.rb', line 51

def select(from: nil, to: nil, &block)
  retval = []

  each_with_depth(from: from, to: to) do |line, depth, index|
    retval << line if (block_given? == false || block.call(line, depth, index))
  end

  retval
end