Class: SassyHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/sassy_hash.rb

Constant Summary collapse

VERSION =
"0.0.5"
VALID_UNIT =
%r{(?<unit>#{::Sass::SCSS::RX::NMSTART}#{::Sass::SCSS::RX::NMCHAR}|%*)}
VALID_NUMBER =
%r{(?<number>#{::Sass::SCSS::RX::NUM})#{VALID_UNIT}}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ SassyHash

Returns a new instance of SassyHash.



15
16
17
18
19
# File 'lib/sassy_hash.rb', line 15

def initialize(*args)
  super(args).tap do |hash|
    hash.sassify!
  end
end

Class Method Details

.[](hash_values) ⇒ Object



9
10
11
12
13
# File 'lib/sassy_hash.rb', line 9

def self.[](hash_values)
  super(hash_values).tap do |hash|
    hash.sassify!
  end
end

.sass_convert_value(value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/sassy_hash.rb', line 35

def self.sass_convert_value(value)
  case value
  when Integer, Float
    return ::Sass::Script::Value::Number.new(value)
  when Symbol
    return ::Sass::Script::Value::String.new(value.to_s)
  when String
    # color
    if value =~ ::Sass::SCSS::RX::HEXCOLOR
      return ::Sass::Script::Value::Color.from_hex(value)
    end
    #number
    if matches = value.match(VALID_NUMBER)
      return ::Sass::Script::Value::Number.new(matches[:number], matches[:unit])
    end
    #string
    return ::Sass::Script::Value::String.new(value)
  when Array
    return ::Sass::Script::Value::List.new(value.map {|v| sass_convert_value(v) }, :sapce)
  when Hash
    return ::Sass::Script::Value::Map.new(self[value])
  when TrueClass, FalseClass
    return ::Sass::Script::Value::Bool.new(value)
  when ::Sass::Script::Value::Base
    return value
  else
    raise SassyHashException, "Non convertable value given" 
  end
end

Instance Method Details

#[]=(key, value) ⇒ Object



29
30
31
32
33
# File 'lib/sassy_hash.rb', line 29

def []=(key, value)
  key = self.class.sass_convert_value(key.to_s)
  value = self.class.sass_convert_value(value)
  super(key, value)
end

#sassify!Object



21
22
23
24
25
26
# File 'lib/sassy_hash.rb', line 21

def sassify!
  keys.each do |key|
    new_key = self.class.sass_convert_value(key.to_s)
    self[new_key] = self.class.sass_convert_value(delete(key))
  end
end