Module | Haml::Util |
In: |
lib/haml/util/subset_map.rb
lib/haml/util.rb |
A module containing various useful functions.
RUBY_VERSION | = | ::RUBY_VERSION.split(".").map {|s| s.to_i} | An array of ints representing the Ruby version number. @api public | |
ENCODINGS_TO_CHECK | = | %w[UTF-8 UTF-16BE UTF-16LE UTF-32BE UTF-32LE] | We could automatically add in any non-ASCII-compatible encodings here, but there‘s not really a good way to do that without manually checking that each encoding encodes all ASCII characters properly, which takes long enough to affect the startup time of the CLI. | |
CHARSET_REGEXPS | = | Hash.new do |h, e| h[e] = begin # /\A(?:\uFEFF)?@charset "(.*?)"|\A(\uFEFF)/ Regexp.new(/\A(?:#{_enc("\uFEFF", e)})?#{ _enc('@charset "', e)}(.*?)#{_enc('"', e)}|\A(#{ _enc("\uFEFF", e)})/) |
@private
# File lib/haml/util.rb, line 520 520: def _enc(string, encoding) 521: string.encode(encoding).force_encoding("BINARY") 522: end
Returns whether this environment is using ActionPack version 3.0.0 or greater.
@return [Boolean]
# File lib/haml/util.rb, line 293 293: def ap_geq_3? 294: # The ActionPack module is always loaded automatically in Rails >= 3 295: return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) 296: 297: version = 298: if defined?(ActionPack::VERSION::MAJOR) 299: ActionPack::VERSION::MAJOR 300: else 301: # Rails 1.2 302: ActionPack::VERSION::Major 303: end 304: 305: version >= 3 306: end
Returns whether this environment is using ActionPack version 3.0.0.beta.3 or greater.
@return [Boolean]
# File lib/haml/util.rb, line 312 312: def ap_geq_3_beta_3? 313: # The ActionPack module is always loaded automatically in Rails >= 3 314: return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) 315: 316: version = 317: if defined?(ActionPack::VERSION::MAJOR) 318: ActionPack::VERSION::MAJOR 319: else 320: # Rails 1.2 321: ActionPack::VERSION::Major 322: end 323: version >= 3 && 324: ((defined?(ActionPack::VERSION::TINY) && 325: ActionPack::VERSION::TINY.is_a?(Fixnum) && 326: ActionPack::VERSION::TINY >= 1) || 327: (defined?(ActionPack::VERSION::BUILD) && 328: ActionPack::VERSION::BUILD =~ /beta(\d+)/ && 329: $1.to_i >= 3)) 330: end
Assert that a given object (usually a String) is HTML safe according to Rails’ XSS handling, if it‘s loaded.
@param text [Object]
# File lib/haml/util.rb, line 372 372: def assert_html_safe!(text) 373: return unless rails_xss_safe? && text && !text.to_s.html_safe? 374: raise Haml::Error.new("Expected #{text.inspect} to be HTML-safe.") 375: end
Returns an ActionView::Template* class. In pre-3.0 versions of Rails, most of these classes were of the form `ActionView::TemplateFoo`, while afterwards they were of the form `ActionView;:Template::Foo`.
@param name [to_s] The name of the class to get.
For example, `:Error` will return `ActionView::TemplateError` or `ActionView::Template::Error`.
# File lib/haml/util.rb, line 340 340: def av_template_class(name) 341: return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}") 342: return ActionView::Template.const_get(name.to_s) 343: end
Returns information about the caller of the previous method.
@param entry [String] An entry in the `caller` list, or a similarly formatted string @return [[String, Fixnum, (String, nil)]] An array containing the filename, line, and method name of the caller.
The method name may be nil
# File lib/haml/util.rb, line 224 224: def caller_info(entry = caller[1]) 225: info = entry.scan(/^(.*?):(-?.*?)(?::.*`(.+)')?$/).first 226: info[1] = info[1].to_i 227: # This is added by Rubinius to designate a block, but we don't care about it. 228: info[2].sub!(/ \{\}\Z/, '') if info[2] 229: info 230: end
Checks that the encoding of a string is valid in Ruby 1.9 and cleans up potential encoding gotchas like the UTF-8 BOM. If it‘s not, yields an error string describing the invalid character and the line on which it occurrs.
@param str [String] The string of which to check the encoding @yield [msg] A block in which an encoding error can be raised.
Only yields if there is an encoding error
@yieldparam msg [String] The error message to be raised @return [String] `str`, potentially with encoding gotchas like BOMs removed
# File lib/haml/util.rb, line 416 416: def check_encoding(str) 417: if ruby1_8? 418: return str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM 419: elsif str.valid_encoding? 420: # Get rid of the Unicode BOM if possible 421: if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/ 422: return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '') 423: else 424: return str 425: end 426: end 427: 428: encoding = str.encoding 429: newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary")) 430: str.force_encoding("binary").split(newlines).each_with_index do |line, i| 431: begin 432: line.encode(encoding) 433: rescue Encoding::UndefinedConversionError => e 434: yield <<MSG.rstrip, i + 1 435: Invalid #{encoding.name} character #{e.error_char.dump} 436: MSG 437: end 438: end 439: return str 440: end
Like {\check_encoding}, but also checks for a Ruby-style `-# coding:` comment at the beginning of the template and uses that encoding if it exists.
The Sass encoding rules are simple. If a `-# coding:` comment exists, we assume that that‘s the original encoding of the document. Otherwise, we use whatever encoding Ruby has.
Haml uses the same rules for parsing coding comments as Ruby. This means that it can understand Emacs-style comments (e.g. `-*- encoding: "utf-8" -*-`), and also that it cannot understand non-ASCII-compatible encodings such as `UTF-16` and `UTF-32`.
@param str [String] The Haml template of which to check the encoding @yield [msg] A block in which an encoding error can be raised.
Only yields if there is an encoding error
@yieldparam msg [String] The error message to be raised @return [String] The original string encoded properly @raise [ArgumentError] if the document declares an unknown encoding
# File lib/haml/util.rb, line 462 462: def check_haml_encoding(str, &block) 463: return check_encoding(str, &block) if ruby1_8? 464: 465: bom, encoding = parse_haml_magic_comment(str) 466: if encoding; str.force_encoding(encoding) 467: elsif bom; str.force_encoding("UTF-8") 468: end 469: 470: return check_encoding(str, &block) 471: end
Like {\check_encoding}, but also checks for a `@charset` declaration at the beginning of the file and uses that encoding if it exists.
The Sass encoding rules are simple. If a `@charset` declaration exists, we assume that that‘s the original encoding of the document. Otherwise, we use whatever encoding Ruby has. Then we convert that to UTF-8 to process internally. The UTF-8 end result is what‘s returned by this method.
@param str [String] The string of which to check the encoding @yield [msg] A block in which an encoding error can be raised.
Only yields if there is an encoding error
@yieldparam msg [String] The error message to be raised @return [(String, Encoding)] The original string encoded as UTF-8,
and the source encoding of the string (or `nil` under Ruby 1.8)
@raise [Encoding::UndefinedConversionError] if the source encoding
cannot be converted to UTF-8
@raise [ArgumentError] if the document uses an unknown encoding with `@charset`
# File lib/haml/util.rb, line 492 492: def check_sass_encoding(str, &block) 493: return check_encoding(str, &block), nil if ruby1_8? 494: # We allow any printable ASCII characters but double quotes in the charset decl 495: bin = str.dup.force_encoding("BINARY") 496: encoding = Haml::Util::ENCODINGS_TO_CHECK.find do |enc| 497: bin =~ Haml::Util::CHARSET_REGEXPS[enc] 498: end 499: charset, bom = $1, $2 500: if charset 501: charset = charset.force_encoding(encoding).encode("UTF-8") 502: if endianness = encoding[/[BL]E$/] 503: begin 504: Encoding.find(charset + endianness) 505: charset << endianness 506: rescue ArgumentError # Encoding charset + endianness doesn't exist 507: end 508: end 509: str.force_encoding(charset) 510: elsif bom 511: str.force_encoding(encoding) 512: end 513: 514: str = check_encoding(str, &block) 515: return str.encode("UTF-8"), str.encoding 516: end
The same as `Kernel#warn`, but is silenced by \{silence_haml_warnings}.
@param msg [String]
# File lib/haml/util.rb, line 257 257: def haml_warn(msg) 258: return if @@silence_warnings 259: warn(msg) 260: end
Returns the given text, marked as being HTML-safe. With older versions of the Rails XSS-safety mechanism, this destructively modifies the HTML-safety of `text`.
@param text [String, nil] @return [String, nil] `text`, marked as HTML-safe
# File lib/haml/util.rb, line 362 362: def html_safe(text) 363: return unless text 364: return text.html_safe if defined?(ActiveSupport::SafeBuffer) 365: text.html_safe! 366: end
Intersperses a value in an enumerable, as would be done with `Array#join` but without concatenating the array together afterwards.
@param enum [Enumerable] @param val @return [Array]
# File lib/haml/util.rb, line 151 151: def intersperse(enum, val) 152: enum.inject([]) {|a, e| a << e << val}[0...-1] 153: end
Computes a single longest common subsequence for `x` and `y`. If there are more than one longest common subsequences, the one returned is that which starts first in `x`.
@param x [Array] @param y [Array] @yield [a, b] An optional block to use in place of a check for equality
between elements of `x` and `y`.
@yieldreturn [Object, nil] If the two values register as equal,
this will return the value to use in the LCS array.
@return [Array] The LCS
# File lib/haml/util.rb, line 212 212: def lcs(x, y, &block) 213: x = [nil, *x] 214: y = [nil, *y] 215: block ||= proc {|a, b| a == b && a} 216: lcs_backtrace(lcs_table(x, y, &block), x, y, x.size-1, y.size-1, &block) 217: end
Maps the key-value pairs of a hash according to a block. For example:
map_hash({:foo => "bar", :baz => "bang"}) {|k, v| [k.to_s, v.to_sym]} #=> {"foo" => :bar, "baz" => :bang}
@param hash [Hash] The hash to map @yield [key, value] A block in which the key-value pairs are transformed @yieldparam [key] The hash key @yieldparam [value] The hash value @yieldreturn [(Object, Object)] The new value for the `[key, value]` pair @return [Hash] The mapped hash @see map_keys @see map_vals
# File lib/haml/util.rb, line 86 86: def map_hash(hash, &block) 87: to_hash(hash.map(&block)) 88: end
Maps the keys in a hash according to a block. For example:
map_keys({:foo => "bar", :baz => "bang"}) {|k| k.to_s} #=> {"foo" => "bar", "baz" => "bang"}
@param hash [Hash] The hash to map @yield [key] A block in which the keys are transformed @yieldparam key [Object] The key that should be mapped @yieldreturn [Object] The new value for the key @return [Hash] The mapped hash @see map_vals @see map_hash
# File lib/haml/util.rb, line 51 51: def map_keys(hash) 52: to_hash(hash.map {|k, v| [yield(k), v]}) 53: end
Maps the values in a hash according to a block. For example:
map_values({:foo => "bar", :baz => "bang"}) {|v| v.to_sym} #=> {:foo => :bar, :baz => :bang}
@param hash [Hash] The hash to map @yield [value] A block in which the values are transformed @yieldparam value [Object] The value that should be mapped @yieldreturn [Object] The new value for the value @return [Hash] The mapped hash @see map_keys @see map_hash
# File lib/haml/util.rb, line 68 68: def map_vals(hash) 69: to_hash(hash.map {|k, v| [k, yield(v)]}) 70: end
Concatenates all strings that are adjacent in an array, while leaving other elements as they are. For example:
merge_adjacent_strings([1, "foo", "bar", 2, "baz"]) #=> [1, "foobar", 2, "baz"]
@param enum [Enumerable] @return [Array] The enumerable with strings merged
# File lib/haml/util.rb, line 130 130: def merge_adjacent_strings(enum) 131: enum.inject([]) do |a, e| 132: if e.is_a?(String) 133: if a.last.is_a?(String) 134: a.last << e 135: else 136: a << e.dup 137: end 138: else 139: a << e 140: end 141: a 142: end 143: end
Return an array of all possible paths through the given arrays.
@param arrs [Array<Array>] @return [Array<Arrays>]
@example paths([[1, 2], [3, 4], [5]]) #=>
# [[1, 3, 5], # [2, 3, 5], # [1, 4, 5], # [2, 4, 5]]
# File lib/haml/util.rb, line 195 195: def paths(arrs) 196: arrs.inject([[]]) do |paths, arr| 197: flatten(arr.map {|e| paths.map {|path| path + [e]}}, 1) 198: end 199: end
Computes the powerset of the given array. This is the set of all subsets of the array. For example:
powerset([1, 2, 3]) #=> Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]
@param arr [Enumerable] @return [Set<Set>] The subsets of `arr`
# File lib/haml/util.rb, line 99 99: def powerset(arr) 100: arr.inject([Set.new].to_set) do |powerset, el| 101: new_powerset = Set.new 102: powerset.each do |subset| 103: new_powerset << subset 104: new_powerset << subset + [el] 105: end 106: new_powerset 107: end 108: end
Returns the environment of the Rails application, if this is running in a Rails context. Returns `nil` if no such environment is defined.
@return [String, nil]
# File lib/haml/util.rb, line 283 283: def rails_env 284: return Rails.env.to_s if defined?(Rails.root) 285: return RAILS_ENV.to_s if defined?(RAILS_ENV) 286: return nil 287: end
Returns the root of the Rails application, if this is running in a Rails context. Returns `nil` if no such root is defined.
@return [String, nil]
# File lib/haml/util.rb, line 269 269: def rails_root 270: if defined?(Rails.root) 271: return Rails.root.to_s if Rails.root 272: raise "ERROR: Rails.root is nil!" 273: end 274: return RAILS_ROOT.to_s if defined?(RAILS_ROOT) 275: return nil 276: end
The class for the Rails SafeBuffer XSS protection class. This varies depending on Rails version.
@return [Class]
# File lib/haml/util.rb, line 381 381: def rails_safe_buffer_class 382: # It's important that we check ActiveSupport first, 383: # because in Rails 2.3.6 ActionView::SafeBuffer exists 384: # but is a deprecated proxy object. 385: return ActiveSupport::SafeBuffer if defined?(ActiveSupport::SafeBuffer) 386: return ActionView::SafeBuffer 387: end
Whether or not ActionView‘s XSS protection is available and enabled, as is the default for Rails 3.0+, and optional for version 2.3.5+. Overridden in haml/template.rb if this is the case.
@return [Boolean]
# File lib/haml/util.rb, line 352 352: def rails_xss_safe? 353: false 354: end
Restricts a number to falling within a given range. Returns the number if it falls within the range, or the closest value in the range if it doesn‘t.
@param value [Numeric] @param range [Range<Numeric>] @return [Numeric]
# File lib/haml/util.rb, line 117 117: def restrict(value, range) 118: [[value, range.first].max, range.last].min 119: end
Whether or not this is running under Ruby 1.8 or lower.
@return [Boolean]
# File lib/haml/util.rb, line 394 394: def ruby1_8? 395: Haml::Util::RUBY_VERSION[0] == 1 && Haml::Util::RUBY_VERSION[1] < 9 396: end
Whether or not this is running under Ruby 1.8.6 or lower. Note that lower versions are not officially supported.
@return [Boolean]
# File lib/haml/util.rb, line 402 402: def ruby1_8_6? 403: ruby1_8? && Haml::Util::RUBY_VERSION[2] < 7 404: end
Silences all Haml warnings within a block.
@yield A block in which no Haml warnings will be printed
# File lib/haml/util.rb, line 246 246: def silence_haml_warnings 247: old_silence_warnings = @@silence_warnings 248: @@silence_warnings = true 249: yield 250: ensure 251: @@silence_warnings = old_silence_warnings 252: end
Silence all output to STDERR within a block.
@yield A block in which no output will be printed to STDERR
# File lib/haml/util.rb, line 235 235: def silence_warnings 236: the_real_stderr, $stderr = $stderr, StringIO.new 237: yield 238: ensure 239: $stderr = the_real_stderr 240: end
Destructively strips whitespace from the beginning and end of the first and last elements, respectively, in the array (if those elements are strings).
@param arr [Array] @return [Array] `arr`
# File lib/haml/util.rb, line 178 178: def strip_string_array(arr) 179: arr.first.lstrip! if arr.first.is_a?(String) 180: arr.last.rstrip! if arr.last.is_a?(String) 181: arr 182: end
Substitutes a sub-array of one array with another sub-array.
@param ary [Array] The array in which to make the substitution @param from [Array] The sequence of elements to replace with `to` @param to [Array] The sequence of elements to replace `from` with
# File lib/haml/util.rb, line 160 160: def substitute(ary, from, to) 161: res = ary.dup 162: i = 0 163: while i < res.size 164: if res[i...i+from.size] == from 165: res[i...i+from.size] = to 166: end 167: i += 1 168: end 169: res 170: end
Converts an array of `[key, value]` pairs to a hash. For example:
to_hash([[:foo, "bar"], [:baz, "bang"]]) #=> {:foo => "bar", :baz => "bang"}
@param arr [Array<(Object, Object)>] An array of pairs @return [Hash] A hash
# File lib/haml/util.rb, line 34 34: def to_hash(arr) 35: arr.compact.inject({}) {|h, (k, v)| h[k] = v; h} 36: end