Class: Stylish::Generate::Variable

Inherits:
Object
  • Object
show all
Defined in:
lib/stylish/generate.rb

Overview

Variables are elements of a selector tree that haven’t been assigned values yet. When a tree that includes Variable objects is serialised, it must be passed a symbol table so that the variables may be given values.

Instance Method Summary collapse

Constructor Details

#initialize(name_or_hash, constructor = nil) ⇒ Variable

When Variable objects are initialised they may be given either a simple symbol, or a compound object (such as a hash) which contains symbols. When a compound object is given, a constructor must also be given.

varbg = Variable.new({:image => :button, :color => :bright})
varbg.to_s({:button => "button.png", :bright => "0f0"})

Which would give the following:

background-image:url('button.png'); background-color:#0f0;

Constructors can also be given for simple values, e.g. when creating a Color.

varc = Variable.new(:bright, Color)
varc.to_s({:bright => "f00"}) # => "#f00"


114
115
116
117
# File 'lib/stylish/generate.rb', line 114

def initialize(name_or_hash, constructor = nil)
  @name        = name_or_hash
  @constructor = constructor
end

Instance Method Details

#eval(name_or_hash, symbol_table) ⇒ Object

Recursively replace symbols with values. This allows for symbol lookup within more complex nested structures of arrays and hashes, created by e.g. background declarations.



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/stylish/generate.rb', line 137

def eval(name_or_hash, symbol_table)
  replaceable = name_or_hash || @name
  
  if replaceable.is_a? Symbol
    if symbol_table[replaceable]
      symbol_table[replaceable]
    else
      raise UndefinedVariable,
        ":#{replaceable.to_s} could not be located in the symbol table."
    end
  elsif replaceable.is_a?(Hash) || replaceable.is_a?(Array)
    replaceable.to_a.inject(replaceable.class.new) do |acc, el|
      if acc.is_a? Hash
        acc[el[0]] = eval(el[1], symbol_table)
      else
        acc << eval(el, symbol_table)
      end
      
      acc
    end
  else
    replaceable
  end
end

#to_s(symbol_table, scope = "") ⇒ Object

The symbol table is given as an argument to the root element of a selector tree when it is serialised, and passed down to each node as the tree is traversed. Nodes must then serialise themselves, and if they contain Variables they must pass them the symbol table so that they can be resolved to a given value.



124
125
126
127
128
129
130
131
132
# File 'lib/stylish/generate.rb', line 124

def to_s(symbol_table, scope = "")
  evald = eval(nil, symbol_table)
  
  unless @constructor.nil?
    @constructor.new(evald).to_s(symbol_table, scope)
  else
    evald
  end
end