task :extract_style do
css = File.read 'public/stylesheets/code.css'
css.gsub! "{\n", '{'
css.gsub! ";\n", ';'
output = ''
output << "module Style\n"
output << " EMBEDED = {\n"
output << css.grep(/\.code pre \.(\w+) \{(.*)\}/) do
" #{(':' + $1).ljust(25)} => '#{$2.delete(' ')}'"
end.join(",\n")
output << "\n }\n"
output << "end"
File.open("app/models/style.rb", 'w') { |f| f << output }
end
Refactorings
No refactoring yet !
hungryblank
September 28, 2007, September 28, 2007 04:39, permalink
I just played some mins around the regexp with no luck
so I came out with this
CssObj.extract_file(filename)
will return an array of objects, each object respond to 'selector' and 'attributes' methods.
Some major cleaning is required
CssObj = Struct.new(:selector, :attributes)
class CssObj
def self.extract_file(filename)
css = File.read(filename)
tokens = css.split(/\}/m)
tokens.map { |token| CssObj.new(*token.split(/\{/m)) }
end
end
macournoyer
September 29, 2007, September 29, 2007 13:45, permalink
Nice one hungryblank! Here I integrated your code into mine and refactored the CssObj class a bit.
class CssObj < Struct.new(:selector, :attributes)
def self.read(filename)
File.read(filename).split(/\}/m).map { |token| CssObj.new(*token.split(/\{/m)) }
end
end
task :extract_style do
output = ''
output << "module Style\n"
output << " EMBEDED = {\n"
output << CssObj.read('public/stylesheets/code.css').collect do |css|
if match = css.selector.match(/\.code pre \.(\w+)/)
" :#{match[1].ljust(24)} => '" <<
css.attributes.delete("\n ") <<
"'"
end
end.compact.join(",\n")
output << "\n }\n"
output << "end"
File.open("app/models/style.rb", 'w') { |f| f << output }
end
Here's a Rake task I use to extract style attributes from a CSS file to later embed it in some HTML (for the pastable version of the code)
I can't seem to match a regex over more then 1 line even with the multiline option. So in trucated the lines before matching them.
There must be a better way of doing this! Any idea ?