0

我正在为 CSS 文件编写一个简单的 ruby​​ 解析器,我对如何获得一个 CSS 块(即选择器以及紧随其后的花括号之间的所有内容)作为一个 ruby​​ 对象感到有些困惑施展我黑暗而肮脏的魔法。

理想情况下,我想获得一个包含每个属性/值和选择器的 ruby​​ 哈希。有什么清晰易懂的方法可以做到这一点吗?

4

2 回答 2

1

正如评论中所提到的,除了有趣的练习之外,自己做是很愚蠢的。我将 css 文件读入字符串,然后用正则表达式扫描它。

Ruby - 将文件转换为字符串

http://www.ruby-doc.org/core-1.9.3/String.html#method-i-scan

用于测试正则表达式:http ://rubular.com/

于 2013-01-07T14:37:20.680 回答
1

每个人都应该写一个解析器。

这应该让你开始......

require 'parslet'
require 'ostruct'
require 'pp'

class Parser < Parslet::Parser
  rule(:opencurl)   { str('{') }
  rule(:closecurl)  { str('}') }
  rule(:space)      { str(' ') }
  rule(:space?)     { space.maybe }
  rule(:comma)      { str(',') }
  rule(:semi)       { str(';') }
  rule(:colon)      { str(':') }
  rule(:eol)        { str("\r").maybe >> str("\n") }
  rule(:eol?)       { eol.maybe }
  rule(:indent?)    { str(" ").repeat(0) }
  rule(:ws?)        {indent? >> eol? >> indent?}

  rule(:value)      { (semi.absent? >> any).repeat(1).as(:value) } #cheating

  rule(:word)       { match['a-zA-Z0-9'].repeat(1) }
  rule(:property)   { (word >> (str("-") >> word).repeat(0)).as(:property) }
  rule(:setting)    { (indent? >> property >> colon >> indent? >> value >> semi  >> eol?) }
  rule(:body?)      { setting.repeat(0).as(:body) }
  rule(:block)      { opencurl >> ws? >> body? >> ws? >> closecurl >> ws? }
  rule(:selector_expression)   { (opencurl.absent? >> any).repeat(1) } #cheating
  rule(:scope)      { ws? >> selector_expression.as("selector") >> indent? >> block.as(:settings) }

  rule(:css?)       { (eol.repeat(0) >> scope).repeat(0) } 
  root(:css?)
end  

class MyTransform < Parslet::Transform
  rule(:property => simple(:p), :value => simple(:v)) { OpenStruct.new(p:p,v:v) }
  rule(:body => sequence(:b)) { b.each_with_object({}){|i,o| o[i.p] = i.v} }
end 

css = <<-css
  h2{ background-image: url(abc);}
  #bob { 
  background-image: url(abc);
  background-color: red;
}
css

par = Parser.new.parse(css)
tar = MyTransform.new.apply(par) 
pp tar

输出:

[{"selector"=>"h2", :settings=>{"background-image"=>"url(abc)"}},
 {"selector"=>"#bob ",
  :settings=>
   {"background-image"=>"url(abc)", "background-color"=>"red"}}]
于 2015-07-13T12:17:08.587 回答