Class: Shepherd::Counter

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

Overview

A simple class that counts all the needed data (like files, lines, bytes and so-on) in given destination path.

Usage

Without using a block:

module Shepherd
   count = Counter.new(/path/to/destination/dir)
   count.files #=> 26
   count.lines #=> 2319
   count.chars #=> 79240
end

With a block:

module Shepherd
   Counter.new(/path/to/destination/dir) do |count|
      count.files #=> 26
      count.lines #=> 2319
      count.chars #=> 79240
   end
end

Inside a Shepherd::Command::Klass you should use it like so:

module Shepherd::Command
   class Klass
      Shepherd::Counter.new(/path/to/destination/dir) do |count|
         count.files #=> 26
         count.lines #=> 2319
         count.chars #=> 79240
      end
   end
end

Yields:

Returns:

Instance Method Summary collapse

Constructor Details

#initialize(path) {|Shepherd::Counter| ... } ⇒ Shepherd::Counter

A new instance of Shepherd::Counter

Parameters:

  • path (String)

    a path to the project

Yields:



46
47
48
49
50
51
# File 'lib/shepherd/counter.rb', line 46

def initialize path
  # delete the last '/' in path if present, just to make sure :)
  @path = path.chomp "/"
  
  yield self if block_given?
end

Instance Method Details

#bytesInteger

Count the bytes. This wont be converted all the time.

Returns:



97
98
99
100
101
102
103
# File 'lib/shepherd/counter.rb', line 97

def bytes
  @bytes = 0
  @files.each do |file|
    @bytes += File.new("#{file}").size
  end
  @bytes
end

#charsInteger

Count the characters.

Returns:



86
87
88
89
90
91
92
# File 'lib/shepherd/counter.rb', line 86

def chars
  @chars = 0
  @files.each do |file|
    @chars += `cat '#{file}' | wc -m`.to_i
  end
  @chars
end

#filesArray

Count the files (excluding dotfiles).

Returns:

  • (Array)

    list of all files (dotfiles are not included)



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/shepherd/counter.rb', line 56

def files
  @files = []
  Find.find(@path) do |path|
    if File.directory? path
      if File.basename(path)[0] == ?.
        Find.prune # don't look any further into this directory.
      else
        next
      end
    else
      @files << path
    end
  end
  @files.size
end

#linesInteger

Count the lines.

Returns:



75
76
77
78
79
80
81
# File 'lib/shepherd/counter.rb', line 75

def lines
  @lines = 0
  @files.each do |file|
    @lines += `cat '#{file}' | wc -l`.to_i
  end
  @lines
end