views:

58

answers:

4

Is there a gem to perform css editing and parsing in Ruby? What I need is to open css file, perform a find by a selector, alter it and save the output. The best way would look as following:

draft = CSSParser.load('structure.css')
draft.find('#header a').style('color', '#333')
draft.render

What's the most appropriate way to do that?

A: 

ruby-css-parser on Google Code looks promising.

Their example page shows parsing and manipulating CSS selectors.

wsanville
Not sure if it's able to change something inside the CSS files. Concat - yes, but what about editing?
gmile
A: 

Try Sass (Sintactically Awesome StyleSheets).

I'm using it and it's awesome!

pablorc
Sass currently unable to mutate css files, - It can only parse.
gmile
I don't know what you're doing, but in my project each client have a different css with corporative colors, and it's 100% sass. Maybe your needs are more complex than mine.
pablorc
A: 

Sass does include a CSS->Sass converter, and you can create 'mixins' and variables to use in your stylesheets. I know it's not exactly what you requested, but depending on what you're attempting to do, it might be a better solution.

Otherwise, it looks like that ruby-css-parser is as close as you're going to get without writing something yourself.

nighthwk1
A: 

I did some steps towards a solution of my problem. Currently the following code is able to alter CSS, although it lacks beautiful finder line draft.find('#header a').style('color', '#333'):

CSS:

$red: #900;

#hello_world a{
  font-size: 1pt + 3pt;

  &:hover{ color: $red + #333 }

  color: #444333;
}

Code:

require 'rubygems'
require 'haml'
require 'sass'

def get_file_as_string(filename)
  data = ''
  File.open(filename, "r").each_line {|line| data += line}
  data
end

engine = Sass::Engine.new(template, :syntax => :scss)
result, extends = engine.to_tree.perform(Sass::Environment.new).cssize

@x = result.children[1] # nice search method should be here

class Sass::Tree::RuleNode
  def set_property(property, value)
    prop = self.children.first{|child| child.class == 'Sass::Tree::PropNode' && child.instance_variable_get(:@resolved_name) == property }
    prop.instance_variable_set(:@resolved_value, value)
  end
end

@x.set_property('color', '#362')

puts result.to_s
gmile