Last active
August 29, 2015 14:06
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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