Skip to content
Browse files

refactor the script into module/class

  • Loading branch information...
1 parent d273a76 commit 48d0fb400f72d02f9b89ee4b1c0fa0d1ab9a5f2f @thomaspierson committed
Showing with 51 additions and 31 deletions.
  1. +51 −31 css2less.rb
View
82 css2less.rb
@@ -1,39 +1,59 @@
#!/usr/bin/ruby
-require 'enumerator'
-def add_rule(tree, selectors, style)
- return if style.nil? || style.empty?
- if selectors.empty?
- (tree[:style] ||= ';') << style
- else
- first, rest = selectors.first, selectors[1..-1]
- node = (tree[first] ||= {})
- add_rule(node, rest, style)
- end
-end
-
-def print_css(tree, indent=0)
- tree.each do |element, children|
- puts ' ' * indent + element + " {\n"
- style = children.delete(:style)
- if style
- puts style.split(';').map { |s| s.strip }.reject { |s| s.empty? }.map { |s| ' ' * (indent+2) + s + ';' }.join("\n")
+module Css2Less
+
+ require 'enumerator'
+
+ class Converter
+
+ def initialize(css)
+ @css = css
+ @tree = {}
+ end
+
+ def add_rule(tree, selectors, style)
+ return if style.nil? || style.empty?
+ if selectors.empty?
+ (tree[:style] ||= ';') << style
+ else
+ first, rest = selectors.first, selectors[1..-1]
+ node = (tree[first] ||= {})
+ add_rule(node, rest, style)
+ end
+ end
+
+ def generate
+ @css.split("\n").map { |l| l.strip }.join.gsub(/\/\*+[^\*]*\*+\//, '').split(/[\{\}]/).each_slice(2) do |style|
+ rules = style[0].strip
+ if rules.include?(',') # leave multiple rules alone
+ add_rule(@tree, [rules], style[1])
+ else
+ add_rule(@tree, rules.split(/\s+/), style[1])
+ end
+ end
end
- print_css(children, indent + 2)
- puts ' ' * indent + "}\n"
+
+ def print(tree=nil, indent=0)
+ if tree.nil?
+ tree = @tree
+ end
+ tree.each do |element, children|
+ puts ' ' * indent + element + " {\n"
+ style = children.delete(:style)
+ if style
+ puts style.split(';').map { |s| s.strip }.reject { |s| s.empty? }.map { |s| ' ' * (indent+2) + s + ';' }.join("\n")
+ end
+ print(children, indent + 2)
+ puts ' ' * indent + "}\n"
+ end
+ end
+
end
+
end
-tree = {}
css = File.read(ARGV[0])
-css.split("\n").map { |l| l.strip }.join.gsub(/\/\*+[^\*]*\*+\//, '').split(/[\{\}]/).each_slice(2) do |style|
- rules = style[0].strip
- if rules.include?(',') # leave multiple rules alone
- add_rule(tree, [rules], style[1])
- else
- add_rule(tree, rules.split(/\s+/), style[1])
- end
-end
-
-print_css(tree)
+converter = Css2Less::Converter.new(css)
+converter.generate
+converter.print

0 comments on commit 48d0fb4

Please sign in to comment.
Something went wrong with that request. Please try again.