Sha256: b63c5ebbc73884493277a53052262f503a07d6b43a2aedd687fb0e1d36e2ee59

Contents?: true

Size: 1.44 KB

Versions: 2

Compression:

Stored size: 1.44 KB

Contents

class CssBuilder

  def initialize
    @css = ''
  end

  def value!
    @css
  end

  def comment!(comment)
    @css << "/* #{comment} */"
    _newline
  end

  def id!(*args, &block)
    _start_tag("##{args[0]}", *args[1..-1], &block)
    @css
  end

  def class!(*args, &block)
    _start_tag(_class(args[0]), *args[1..-1], &block)
    @css
  end

  def method_missing(m, *args, &block)

    if block
      _start_tag(m, *args, &block)
    else
      _indent
      css! _dasherize m
      css! " : #{args.first};"
      _newline
    end
   
    @css
  end

private

  def _start_tag(value, *args, &block)
    css! _dasherize(value)

    _args_tag_values(args)

    _open
    _newline 

    self.instance_eval(&block)

    _close
    _newline
  end

  def css!(val)
    @css << val
  end

  def _newline
    css! "\n"
  end

  def _close
    css! "}"
  end

  def _open
    css! " {"
  end

  def _indent
    css! "  "
  end

  def _class(v)
    ".#{v.strip.gsub(/\s+/, '.')}"
  end

  def _dasherize(v)
    v.to_s.gsub(/_/, '-')
  end

  def _args_tag_values(args)
    args.each do |arg|
      case arg
      when ::Array
        _args_tag_values(arg)
        css! " "
      when ::Hash
        _args_hash_values(arg)
      else
      end
    end
  end

  def _args_hash_values(hash)
    hash.each do |k,v|
      case k
      when :id
        css! "##{v}"
      when :class
        css! _class(v)
      else
        css! ":#{_dasherize k}(#{v})"
      end
    end
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
css_builder-0.1.1 lib/css_builder.rb
css_builder-0.1.0 lib/css_builder.rb