Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Last active December 11, 2015 06:58
Show Gist options
  • Save jamesmartin/4562865 to your computer and use it in GitHub Desktop.
Save jamesmartin/4562865 to your computer and use it in GitHub Desktop.
The Flog score of your Rails ERB templates.
require 'action_view'
require 'ostruct'
require 'erb'
require 'flog'
require 'ruby_parser'
require 'sexp_processor'
ERBHandler = ActionView::Template::Handlers::ERB.new
def new_template(body, details={format: :html})
ActionView::Template.new(body, "irrelevant", details.fetch(:handler) {ERBHandler}, details)
end
def sort_by_combined_score(totals)
totals.sort do |a, b|
b[1].values.inject(&:+) <=> a[1].values.inject(&:+)
end
end
if $0 == __FILE__
src_dir = ARGV[0]
raise ArgumentError, "Supply a path containing ERB templates" unless src_dir
puts "Contemplating ERB templates from: #{src_dir}"
erb_files = Dir.glob(File.join(src_dir, "**/*.erb"))
totals = erb_files.inject({}) do |totals, file|
erb_source = File.read(file)
ruby_source = ERBHandler.call(new_template(erb_source))
sexp_parsed = RubyParser.new.parse(ruby_source)
flog = Flog.new
flog.process(sexp_parsed)
totals[file] = flog.totals
totals
end
sort_by_combined_score(totals).each do |filename, totals|
puts "#{filename} : #{totals}"
end
end
@jamesmartin
Copy link
Author

Run it like this:
ruby contemplative.rb /path/to/your/rails/app/

Get output like this (templates sorted by Flog score):

foo/app/views/walruses/edit.html.erb : {"main#none"=>54.5979853108153, "some#method"=>7.593418202627854}
foo/app/views/walruses/new.html.erb : {"main#none"=>26.214690537940754}
foo/app/views/walruses/about.html.erb : {"main#none"=>3.830143600441112}

@lukeholder
Copy link

Keep in mind that templates can have multiple extension.

The order of these preprocessors is important. For example, if you called your JavaScript file app/assets/javascripts/projects.js.erb.coffee then it would be processed with the CoffeeScript interpreter first, which wouldn’t understand ERB and therefore you would run into problems.

@benjaminwood
Copy link

Thanks for this. With the latest version of flog you need to call flog.calculate_total_scores before calling flog.totals. See here: http://docs.seattlerb.org/flog/Flog.html#method-i-calculate_total_scores

I've add the line in the fork here: https://gist.github.com/benjaminwood/9744892

@benjaminwood
Copy link

Anybody know how to get the ruby source from a haml file? I've spent a bit of time on this already but couldn't figure it out. It'd be cool to run this against ERB and then again after converting to HAML and refactoring.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment