2008-12-28 01:34:52 -05:00
|
|
|
require 'erb'
|
|
|
|
require 'set'
|
2009-01-22 17:53:59 -05:00
|
|
|
require 'enumerator'
|
2008-12-28 01:34:52 -05:00
|
|
|
|
2008-11-22 22:17:06 -05:00
|
|
|
module Haml
|
|
|
|
module Util
|
2009-04-22 16:45:26 -04:00
|
|
|
extend self
|
2008-11-22 22:17:06 -05:00
|
|
|
|
2009-01-22 19:29:02 -05:00
|
|
|
RUBY_VERSION = ::RUBY_VERSION.split(".").map {|s| s.to_i}
|
|
|
|
|
2008-11-22 22:17:06 -05:00
|
|
|
def to_hash(arr)
|
|
|
|
arr.compact.inject({}) {|h, (k, v)| h[k] = v; h}
|
|
|
|
end
|
|
|
|
|
|
|
|
def map_keys(hash)
|
|
|
|
to_hash(hash.map {|k, v| [yield(k), v]})
|
|
|
|
end
|
|
|
|
|
|
|
|
def map_vals(hash)
|
|
|
|
to_hash(hash.map {|k, v| [k, yield(v)]})
|
|
|
|
end
|
|
|
|
|
|
|
|
def map_hash(hash, &block)
|
|
|
|
to_hash(hash.map(&block))
|
|
|
|
end
|
2008-12-28 01:34:52 -05:00
|
|
|
|
|
|
|
def powerset(arr)
|
|
|
|
arr.inject([Set.new].to_set) do |powerset, el|
|
|
|
|
new_powerset = Set.new
|
|
|
|
powerset.each do |subset|
|
|
|
|
new_powerset << subset
|
|
|
|
new_powerset << subset + [el]
|
|
|
|
end
|
|
|
|
new_powerset
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2009-03-28 02:13:59 -04:00
|
|
|
def merge_adjacent_strings(enum)
|
|
|
|
e = enum.inject([]) do |a, e|
|
|
|
|
if e.is_a?(String) && a.last.is_a?(String)
|
|
|
|
a.last << e
|
|
|
|
else
|
|
|
|
a << e
|
|
|
|
end
|
|
|
|
a
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2009-01-22 19:29:02 -05:00
|
|
|
def ruby1_8?
|
|
|
|
Haml::Util::RUBY_VERSION[0] == 1 && Haml::Util::RUBY_VERSION[1] < 9
|
|
|
|
end
|
|
|
|
|
|
|
|
def has?(attr, klass, method)
|
|
|
|
klass.send("#{attr}s").include?(ruby1_8? ? method.to_s : method.to_sym)
|
|
|
|
end
|
2009-01-22 19:40:44 -05:00
|
|
|
|
2009-01-22 17:53:59 -05:00
|
|
|
def enum_with_index(enum)
|
|
|
|
ruby1_8? ? enum.enum_with_index : enum.each_with_index
|
|
|
|
end
|
|
|
|
|
2008-12-28 01:34:52 -05:00
|
|
|
class StaticConditionalContext
|
|
|
|
def initialize(set)
|
|
|
|
@set = set
|
|
|
|
end
|
|
|
|
|
|
|
|
def method_missing(name, *args, &block)
|
|
|
|
super unless args.empty? && block.nil?
|
|
|
|
@set.include?(name)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def def_static_method(klass, name, args, *vars)
|
|
|
|
erb = vars.pop
|
|
|
|
powerset(vars).each do |set|
|
|
|
|
context = StaticConditionalContext.new(set).instance_eval {binding}
|
|
|
|
klass.class_eval(<<METHOD)
|
|
|
|
def #{static_method_name(name, *vars.map {|v| set.include?(v)})}(#{args.join(', ')})
|
|
|
|
#{ERB.new(erb).result(context)}
|
|
|
|
end
|
|
|
|
METHOD
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def static_method_name(name, *vars)
|
|
|
|
"#{name}_#{vars.map {|v| !!v}.join('_')}"
|
|
|
|
end
|
2008-11-22 22:17:06 -05:00
|
|
|
end
|
|
|
|
end
|