Commits

Shrikant Sharat Kandula  committed 923a521

Refactored to avoid code repetition.

  • Participants
  • Parent commits 0b555b9

Comments (0)

Files changed (1)

 
 require 'nokogiri'
 
-f = File.open 'index.html'
-doc = Nokogiri::HTML f
-f.close
+File.open 'index.html' do |f|
+  @doc = Nokogiri::HTML f
+end
+
+def combine_and_save(combined_filename, selector, attribute)
+  File.open combined_filename, 'w' do |outfile|
+    @doc.css(selector).each_with_index do |asset, i|
+
+      filename = asset[attribute]
+
+      File.open filename do |f|
+        outfile.write f.reduce { |acc, line| acc + line }
+      end
+
+      if i.zero?
+        asset[attribute] = combined_filename
+      else
+        asset.remove
+      end
+
+    end
+  end
+end
 
 combined_js = 'all-scripts.js'
 combined_css = 'all-styles.css'
 
-File.open combined_js, 'w' do |outfile|
-  doc.css('script').each_with_index do |script, i|
-    filename = script[:src]
-    File.open filename do |f|
-      outfile.write f.reduce { |acc, line| acc + line }
-    end
-    if i.zero?
-      script[:src] = combined_js
-    else
-      script.remove unless i == 0
-    end
-  end
+combine_and_save combined_js, 'script', :src
+combine_and_save combined_css, 'link[rel=stylesheet]', :href
+
+File.open 'index-out.html', 'w' do |outfile|
+  outfile.write @doc
 end
 
-# FIXME: Code repetition.
-File.open combined_css, 'w' do |outfile|
-  doc.css('link[rel=stylesheet]').each_with_index do |asset, i|
-    filename = asset[:href]
-    File.open filename do |f|
-      outfile.write f.reduce { |acc, line| acc + line }
-    end
-    if i.zero?
-      asset[:src] = combined_css
-    else
-      asset.remove unless i == 0
-    end
-  end
-end
-
-File.open 'index-out.html', 'w' do |outfile|
-  outfile.write doc
-end
-
-puts 'Done'
+puts 'Fin'