Skip to content

Instantly share code, notes, and snippets.

@jeremysmithco
Last active August 29, 2015 14:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jeremysmithco/9cf106e591e78de282fb to your computer and use it in GitHub Desktop.
Count words in your Rails app, just pass it the path to your views directory (or a subdirectory) to get the word count from your ERB files.
#!/usr/bin/env ruby
require "action_view"
require "fileutils"
class WordCounter
include ActionView::Helpers::SanitizeHelper
def initialize(initial_directory)
@initial_directory = initial_directory
puts count_directory(@initial_directory)
end
def count_directory(directory)
return 0 if !File.directory?(directory)
word_count_total = 0
FileUtils.cd(directory) do
files = Dir.glob("**/*")
files.each do |file_name|
full_path = "#{directory}/#{file_name}"
if File.directory?(full_path)
word_count_total += count_directory(full_path)
elsif File.exists?(full_path)
word_count_total += word_count(strip_html(strip_comments(strip_erb(File.read(full_path)))))
end
end
end
return word_count_total
end
private
def strip_erb(text)
text.gsub(/<%(?:(?!%>).)+%>/, "")
end
def strip_comments(text)
text.gsub(/<!--\s+-->/, "")
end
def strip_html(text)
sanitize(text, :tags => [], :attributes => [])
end
def word_count(text)
text.split.length rescue 0
end
end
WordCounter.new(ARGV[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment