module Haml::Util
def _enc(string, encoding)
- Private: -
def _enc(string, encoding) string.encode(encoding).force_encoding("BINARY") end
def ap_geq?(version)
-
(Boolean)
-
Parameters:
-
version
(String
) -- The string version number to check against.
def ap_geq?(version) # The ActionPack module is always loaded automatically in Rails >= 3 return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) && defined?(ActionPack::VERSION::STRING) ActionPack::VERSION::STRING >= version end
def ap_geq_3?
-
(Boolean)
-
def ap_geq_3? ap_geq?("3.0.0.beta1") end
def assert_html_safe!(text)
-
text
(Object
) --
def assert_html_safe!(text) return unless rails_xss_safe? && text && !text.to_s.html_safe? raise Haml::Error.new("Expected #{text.inspect} to be HTML-safe.") end
def av_template_class(name)
-
name
(#to_s
) -- The name of the class to get.
def av_template_class(name) return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}") return ActionView::Template.const_get(name.to_s) end
def caller_info(entry = caller[1])
-
([String, Fixnum, (String, nil)])
- An array containing the filename, line, and method name of the caller.
Parameters:
-
entry
(String
) -- An entry in the `#caller` list, or a similarly formatted string
def caller_info(entry = caller[1]) info = entry.scan(/^(.*?):(-?.*?)(?::.*`(.+)')?$/).first info[1] = info[1].to_i # This is added by Rubinius to designate a block, but we don't care about it. info[2].sub!(/ \{\}\Z/, '') if info[2] info end
def check_encoding(str)
-
(String)
- `str`, potentially with encoding gotchas like BOMs removed
Other tags:
- Yieldparam: msg - The error message to be raised
Other tags:
- Yield: - A block in which an encoding error can be raised.
Parameters:
-
str
(String
) -- The string of which to check the encoding
def check_encoding(str) if ruby1_8? return str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM elsif str.valid_encoding? # Get rid of the Unicode BOM if possible if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/ return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '') else return str end end encoding = str.encoding newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary")) str.force_encoding("binary").split(newlines).each_with_index do |line, i| begin line.encode(encoding) rescue Encoding::UndefinedConversionError => e yield <<MSG.rstrip, i + 1 lid #{encoding.name} character #{e.error_char.dump} end end return str end
def check_haml_encoding(str, &block)
-
(ArgumentError)
- if the document declares an unknown encoding
Returns:
-
(String)
- The original string encoded properly
Other tags:
- Yieldparam: msg - The error message to be raised
Other tags:
- Yield: - A block in which an encoding error can be raised.
Parameters:
-
str
(String
) -- The Haml template of which to check the encoding
def check_haml_encoding(str, &block) return check_encoding(str, &block) if ruby1_8? bom, encoding = parse_haml_magic_comment(str) if encoding; str.force_encoding(encoding) elsif bom; str.force_encoding("UTF-8") end return check_encoding(str, &block) end
def check_sass_encoding(str, &block)
-
(ArgumentError)
- if the document uses an unknown encoding with `@charset` -
(Encoding::UndefinedConversionError)
- if the source encoding
Returns:
-
((String, Encoding))
- The original string encoded as UTF-8,
Other tags:
- Yieldparam: msg - The error message to be raised
Other tags:
- Yield: - A block in which an encoding error can be raised.
Parameters:
-
str
(String
) -- The string of which to check the encoding
def check_sass_encoding(str, &block) return check_encoding(str, &block), nil if ruby1_8? # We allow any printable ASCII characters but double quotes in the charset decl bin = str.dup.force_encoding("BINARY") encoding = Haml::Util::ENCODINGS_TO_CHECK.find do |enc| bin =~ Haml::Util::CHARSET_REGEXPS[enc] end charset, bom = $1, $2 if charset charset = charset.force_encoding(encoding).encode("UTF-8") if endianness = encoding[/[BL]E$/] begin Encoding.find(charset + endianness) charset << endianness rescue ArgumentError # Encoding charset + endianness doesn't exist end end str.force_encoding(charset) elsif bom str.force_encoding(encoding) end str = check_encoding(str, &block) return str.encode("UTF-8"), str.encoding end
def def_static_method(klass, name, args, *vars)
-
erb
(String
) -- The template for the method code -
vars
(Array
) -- The names of the static boolean variables -
args
(Array
) -- The names of the arguments to the defined methods -
name
(#to_s
) -- The (base) name of the static method -
klass
(Module
) -- The class on which to define the static method
Overloads:
-
def_static_method(klass, name, args, *vars, erb)
def def_static_method(klass, name, args, *vars) erb = vars.pop info = caller_info powerset(vars).each do |set| context = StaticConditionalContext.new(set).instance_eval {binding} klass.class_eval(<<METHOD, info[0], info[1]) #{static_method_name(name, *vars.map {|v| set.include?(v)})}(#{args.join(', ')}) ERB.new(erb).result(context)} OD end end
def enum_cons(enum, n)
-
(Enumerator)
- The consed enumerator
Parameters:
-
n
(Fixnum
) -- The size of each cons -
enum
(Enumerable
) -- The enumerable to get the enumerator for
def enum_cons(enum, n) ruby1_8? ? enum.enum_cons(n) : enum.each_cons(n) end
def enum_slice(enum, n)
-
(Enumerator)
- The consed enumerator
Parameters:
-
n
(Fixnum
) -- The size of each slice -
enum
(Enumerable
) -- The enumerable to get the enumerator for
def enum_slice(enum, n) ruby1_8? ? enum.enum_slice(n) : enum.each_slice(n) end
def enum_with_index(enum)
-
(Enumerator)
- The with-index enumerator
Parameters:
-
enum
(Enumerable
) -- The enumerable to get the enumerator for
def enum_with_index(enum) ruby1_8? ? enum.enum_with_index : enum.each_with_index end
def flatten(arr, n)
-
(Array)
- The flattened array
Parameters:
-
n
(Fixnum
) -- The number of levels to flatten -
arr
(Array
) -- The array to flatten
def flatten(arr, n) return arr.flatten(n) unless ruby1_8_6? return arr if n == 0 arr.inject([]) {|res, e| e.is_a?(Array) ? res.concat(flatten(e, n - 1)) : res << e} end
def haml_warn(msg)
-
msg
(String
) --
def haml_warn(msg) return if @@silence_warnings warn(msg) end
def has?(attr, klass, method)
-
(Boolean)
- Whether or not the given collection has the given method
Parameters:
-
method
(String, Symbol
) -- The name of the method do check for -
klass
(Module
) -- The class to check the methods of which to check -
attr
(#to_s
) -- The (singular) name of the method-collection method
def has?(attr, klass, method) klass.send("#{attr}s").include?(ruby1_8? ? method.to_s : method.to_sym) end
def html_safe(text)
-
(String, nil)
- `text`, marked as HTML-safe
Parameters:
-
text
(String, nil
) --
def html_safe(text) return unless text return text.html_safe if defined?(ActiveSupport::SafeBuffer) text.html_safe! end
def intersperse(enum, val)
-
(Array)
-
Parameters:
-
val
() --
-
enum
(Enumerable
) --
def intersperse(enum, val) enum.inject([]) {|a, e| a << e << val}[0...-1] end
def lcs(x, y, &block)
-
(Array)
- The LCS
Other tags:
- Yieldreturn: - If the two values register as equal,
Other tags:
- Yield: - An optional block to use in place of a check for equality
Parameters:
-
y
(Array
) -- -
x
(Array
) --
def lcs(x, y, &block) x = [nil, *x] y = [nil, *y] block ||= proc {|a, b| a == b && a} lcs_backtrace(lcs_table(x, y, &block), x, y, x.size-1, y.size-1, &block) end
def lcs_backtrace(c, x, y, i, j, &block)
Computes a single longest common subsequence for arrays x and y.
def lcs_backtrace(c, x, y, i, j, &block) return [] if i == 0 || j == 0 if v = yield(x[i], y[j]) return lcs_backtrace(c, x, y, i-1, j-1, &block) << v end return lcs_backtrace(c, x, y, i, j-1, &block) if c[i][j-1] > c[i-1][j] return lcs_backtrace(c, x, y, i-1, j, &block) end
def lcs_table(x, y)
Calculates the memoization table for the Least Common Subsequence algorithm.
def lcs_table(x, y) c = Array.new(x.size) {[]} x.size.times {|i| c[i][0] = 0} y.size.times {|j| c[0][j] = 0} (1...x.size).each do |i| (1...y.size).each do |j| c[i][j] = if yield x[i], y[j] c[i-1][j-1] + 1 else [c[i][j-1], c[i-1][j]].max end end end return c end
def map_hash(hash, &block)
- See: #map_vals -
See: #map_keys -
Returns:
-
(Hash)
- The mapped hash
Other tags:
- Yieldreturn: - The new value for the `[key, value]` pair
Other tags:
- Yieldparam: The - hash value
Yieldparam: The - hash key
Other tags:
- Yield: - A block in which the key-value pairs are transformed
Parameters:
-
hash
(Hash
) -- The hash to map
def map_hash(hash, &block) to_hash(hash.map(&block)) end
def map_keys(hash)
- See: #map_hash -
See: #map_vals -
Returns:
-
(Hash)
- The mapped hash
Other tags:
- Yieldreturn: - The new value for the key
Other tags:
- Yieldparam: key - The key that should be mapped
Other tags:
- Yield: - A block in which the keys are transformed
Parameters:
-
hash
(Hash
) -- The hash to map
def map_keys(hash) to_hash(hash.map {|k, v| [yield(k), v]}) end
def map_vals(hash)
- See: #map_hash -
See: #map_keys -
Returns:
-
(Hash)
- The mapped hash
Other tags:
- Yieldreturn: - The new value for the value
Other tags:
- Yieldparam: value - The value that should be mapped
Other tags:
- Yield: - A block in which the values are transformed
Parameters:
-
hash
(Hash
) -- The hash to map
def map_vals(hash) to_hash(hash.map {|k, v| [k, yield(v)]}) end
def merge_adjacent_strings(enum)
-
(Array)
- The enumerable with strings merged
Parameters:
-
enum
(Enumerable
) --
def merge_adjacent_strings(enum) enum.inject([]) do |a, e| if e.is_a?(String) if a.last.is_a?(String) a.last << e else a << e.dup end else a << e end a end end
def ord(c)
-
(Fixnum)
- The ASCII code of `c`.
Parameters:
-
c
(String
) -- All characters but the first are ignored.
def ord(c) ruby1_8? ? c[0] : c.ord end
def parse_haml_magic_comment(str)
-
((Boolean, String or nil))
-
def parse_haml_magic_comment(str) scanner = StringScanner.new(str.dup.force_encoding("BINARY")) bom = scanner.scan(/\xEF\xBB\xBF/n) return bom unless scanner.scan(/-\s*#\s*/n) if coding = try_parse_haml_emacs_magic_comment(scanner) return bom, coding end return bom unless scanner.scan(/.*?coding[=:]\s*([\w-]+)/in) return bom, scanner[1] end
def paths(arrs)
-
(Array
-)
Parameters:
-
arrs
(Array
) --
def paths(arrs) arrs.inject([[]]) do |paths, arr| flatten(arr.map {|e| paths.map {|path| path + [e]}}, 1) end end
def powerset(arr)
-
(Set
- The subsets of `arr`)
Parameters:
-
arr
(Enumerable
) --
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
def rails_env
-
(String, nil)
-
def rails_env return Rails.env.to_s if defined?(Rails.root) return RAILS_ENV.to_s if defined?(RAILS_ENV) return nil end
def rails_root
-
(String, nil)
-
def rails_root if defined?(Rails.root) return Rails.root.to_s if Rails.root raise "ERROR: Rails.root is nil!" end return RAILS_ROOT.to_s if defined?(RAILS_ROOT) return nil end
def rails_safe_buffer_class
-
(Class)
-
def rails_safe_buffer_class # It's important that we check ActiveSupport first, # because in Rails 2.3.6 ActionView::SafeBuffer exists # but is a deprecated proxy object. return ActiveSupport::SafeBuffer if defined?(ActiveSupport::SafeBuffer) return ActionView::SafeBuffer end
def rails_xss_safe?
-
(Boolean)
-
def rails_xss_safe? false end
def restrict(value, range)
-
(Numeric)
-
Parameters:
-
range
(Range
) -- -
value
(Numeric
) --
def restrict(value, range) [[value, range.first].max, range.last].min end
def ruby1_8?
-
(Boolean)
-
def ruby1_8? Haml::Util::RUBY_VERSION[0] == 1 && Haml::Util::RUBY_VERSION[1] < 9 end
def ruby1_8_6?
-
(Boolean)
-
def ruby1_8_6? ruby1_8? && Haml::Util::RUBY_VERSION[2] < 7 end
def scope(file)
-
(String)
- The filename relative to the the working directory
Parameters:
-
file
(String
) -- The filename relative to the Haml root
def scope(file) File.join(Haml::ROOT_DIR, file) end
def set_eql?(set1, set2)
-
(Boolean)
- Whether or not the sets are hashcode equal
Parameters:
-
set2
(Set
) -- -
set1
(Set
) --
def set_eql?(set1, set2) return set1.eql?(set2) unless ruby1_8_6? set1.to_a.uniq.sort_by {|e| e.hash}.eql?(set2.to_a.uniq.sort_by {|e| e.hash}) end
def set_hash(set)
-
(Fixnum)
- The order-independent hashcode of `set`
Parameters:
-
set
(Set
) --
def set_hash(set) return set.hash unless ruby1_8_6? set.map {|e| e.hash}.uniq.sort.hash end
def silence_haml_warnings
- Yield: - A block in which no Haml warnings will be printed
def silence_haml_warnings old_silence_warnings = @@silence_warnings @@silence_warnings = true yield ensure @@silence_warnings = old_silence_warnings end
def silence_warnings
- Yield: - A block in which no output will be printed to STDERR
def silence_warnings the_real_stderr, $stderr = $stderr, StringIO.new yield ensure $stderr = the_real_stderr end
def static_method_name(name, *vars)
-
(String)
- The real name of the static method
Parameters:
-
vars
(Array
) -- The static variable assignment -
name
(String
) -- The base name of the static method
def static_method_name(name, *vars) "#{name}_#{vars.map {|v| !!v}.join('_')}" end
def strip_string_array(arr)
-
(Array)
- `arr`
Parameters:
-
arr
(Array
) --
def strip_string_array(arr) arr.first.lstrip! if arr.first.is_a?(String) arr.last.rstrip! if arr.last.is_a?(String) arr end
def substitute(ary, from, to)
-
to
(Array
) -- The sequence of elements to replace `from` with -
from
(Array
) -- The sequence of elements to replace with `to` -
ary
(Array
) -- The array in which to make the substitution
def substitute(ary, from, to) res = ary.dup i = 0 while i < res.size if res[i...i+from.size] == from res[i...i+from.size] = to end i += 1 end res end
def to_hash(arr)
-
(Hash)
- A hash
Parameters:
-
arr
(Array<(Object, Object)>
) -- An array of pairs
def to_hash(arr) arr.compact.inject({}) {|h, (k, v)| h[k] = v; h} end
def try_parse_haml_emacs_magic_comment(scanner)
def try_parse_haml_emacs_magic_comment(scanner) pos = scanner.pos return unless scanner.scan(/.*?-\*-\s*/n) # From Ruby's parse.y return unless scanner.scan(/([^\s'":;]+)\s*:\s*("(?:\\.|[^"])*"|[^"\s;]+?)[\s;]*-\*-/n) name, val = scanner[1], scanner[2] return unless name =~ /(en)?coding/in val = $1 if val =~ /^"(.*)"$/n return val ensure scanner.pos = pos end