| 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 | |
| RUBY_ENGINE | = | defined?(::RUBY_ENGINE) ? ::RUBY_ENGINE : "ruby" | The Ruby engine we‘re running under. Defaults to `"ruby"` if the top-level constant is undefined. @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 567
567: def _enc(string, encoding)
568: string.encode(encoding).force_encoding("BINARY")
569: end
Returns whether this environment is using ActionPack of a version greater than or equal to that specified.
@param version [String] The string version number to check against.
Should be greater than or equal to Rails 3, because otherwise ActionPack::VERSION isn't autoloaded
@return [Boolean]
# File lib/haml/util.rb, line 349
349: def ap_geq?(version)
350: # The ActionPack module is always loaded automatically in Rails >= 3
351: return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
352: defined?(ActionPack::VERSION::STRING)
353:
354: version_geq(ActionPack::VERSION::STRING, version)
355: end
Returns whether this environment is using ActionPack version 3.0.0 or greater.
@return [Boolean]
# File lib/haml/util.rb, line 338
338: def ap_geq_3?
339: ap_geq?("3.0.0.beta1")
340: 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 397
397: def assert_html_safe!(text)
398: return unless rails_xss_safe? && text && !text.to_s.html_safe?
399: raise Haml::Error.new("Expected #{text.inspect} to be HTML-safe.")
400: 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 365
365: def av_template_class(name)
366: return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
367: return ActionView::Template.const_get(name.to_s)
368: 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 231
231: def caller_info(entry = caller[1])
232: info = entry.scan(/^(.*?):(-?.*?)(?::.*`(.+)')?$/).first
233: info[1] = info[1].to_i
234: # This is added by Rubinius to designate a block, but we don't care about it.
235: info[2].sub!(/ \{\}\Z/, '') if info[2]
236: info
237: 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 462
462: def check_encoding(str)
463: if ruby1_8?
464: return str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM
465: elsif str.valid_encoding?
466: # Get rid of the Unicode BOM if possible
467: if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/
468: return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '')
469: else
470: return str
471: end
472: end
473:
474: encoding = str.encoding
475: newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary"))
476: str.force_encoding("binary").split(newlines).each_with_index do |line, i|
477: begin
478: line.encode(encoding)
479: rescue Encoding::UndefinedConversionError => e
480: yield <<MSG.rstrip, i + 1
481: Invalid #{encoding.name} character #{e.error_char.dump}
482: MSG
483: end
484: end
485: return str
486: 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 508
508: def check_haml_encoding(str, &block)
509: return check_encoding(str, &block) if ruby1_8?
510: str = str.dup if str.frozen?
511:
512: bom, encoding = parse_haml_magic_comment(str)
513: if encoding; str.force_encoding(encoding)
514: elsif bom; str.force_encoding("UTF-8")
515: end
516:
517: return check_encoding(str, &block)
518: 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 539
539: def check_sass_encoding(str, &block)
540: return check_encoding(str, &block), nil if ruby1_8?
541: # We allow any printable ASCII characters but double quotes in the charset decl
542: bin = str.dup.force_encoding("BINARY")
543: encoding = Haml::Util::ENCODINGS_TO_CHECK.find do |enc|
544: bin =~ Haml::Util::CHARSET_REGEXPS[enc]
545: end
546: charset, bom = $1, $2
547: if charset
548: charset = charset.force_encoding(encoding).encode("UTF-8")
549: if endianness = encoding[/[BL]E$/]
550: begin
551: Encoding.find(charset + endianness)
552: charset << endianness
553: rescue ArgumentError # Encoding charset + endianness doesn't exist
554: end
555: end
556: str.force_encoding(charset)
557: elsif bom
558: str.force_encoding(encoding)
559: end
560:
561: str = check_encoding(str, &block)
562: return str.encode("UTF-8"), str.encoding
563: end
The same as `Kernel#warn`, but is silenced by \{silence_haml_warnings}.
@param msg [String]
# File lib/haml/util.rb, line 302
302: def haml_warn(msg)
303: return if @@silence_warnings
304: warn(msg)
305: 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 387
387: def html_safe(text)
388: return unless text
389: return text.html_safe if defined?(ActiveSupport::SafeBuffer)
390: text.html_safe!
391: 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 158
158: def intersperse(enum, val)
159: enum.inject([]) {|a, e| a << e << val}[0...-1]
160: end
Whether or not this is running on IronRuby.
@return [Boolean]
# File lib/haml/util.rb, line 426
426: def ironruby?
427: RUBY_ENGINE == "ironruby"
428: 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 219
219: def lcs(x, y, &block)
220: x = [nil, *x]
221: y = [nil, *y]
222: block ||= proc {|a, b| a == b && a}
223: lcs_backtrace(lcs_table(x, y, &block), x, y, x.size-1, y.size-1, &block)
224: 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 93
93: def map_hash(hash, &block)
94: to_hash(hash.map(&block))
95: 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 58
58: def map_keys(hash)
59: to_hash(hash.map {|k, v| [yield(k), v]})
60: 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 75
75: def map_vals(hash)
76: to_hash(hash.map {|k, v| [k, yield(v)]})
77: 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 137
137: def merge_adjacent_strings(enum)
138: enum.inject([]) do |a, e|
139: if e.is_a?(String)
140: if a.last.is_a?(String)
141: a.last << e
142: else
143: a << e.dup
144: end
145: else
146: a << e
147: end
148: a
149: end
150: 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 202
202: def paths(arrs)
203: arrs.inject([[]]) do |paths, arr|
204: flatten(arr.map {|e| paths.map {|path| path + [e]}}, 1)
205: end
206: 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 106
106: def powerset(arr)
107: arr.inject([Set.new].to_set) do |powerset, el|
108: new_powerset = Set.new
109: powerset.each do |subset|
110: new_powerset << subset
111: new_powerset << subset + [el]
112: end
113: new_powerset
114: end
115: 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 328
328: def rails_env
329: return ::Rails.env.to_s if defined?(::Rails.env)
330: return RAILS_ENV.to_s if defined?(RAILS_ENV)
331: return nil
332: 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 314
314: def rails_root
315: if defined?(::Rails.root)
316: return ::Rails.root.to_s if ::Rails.root
317: raise "ERROR: Rails.root is nil!"
318: end
319: return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
320: return nil
321: end
The class for the Rails SafeBuffer XSS protection class. This varies depending on Rails version.
@return [Class]
# File lib/haml/util.rb, line 406
406: def rails_safe_buffer_class
407: # It's important that we check ActiveSupport first,
408: # because in Rails 2.3.6 ActionView::SafeBuffer exists
409: # but is a deprecated proxy object.
410: return ActiveSupport::SafeBuffer if defined?(ActiveSupport::SafeBuffer)
411: return ActionView::SafeBuffer
412: 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 377
377: def rails_xss_safe?
378: false
379: 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 124
124: def restrict(value, range)
125: [[value, range.first].max, range.last].min
126: end
Whether or not this is running under Ruby 1.8 or lower.
Note that IronRuby counts as Ruby 1.8, because it doesn‘t support the Ruby 1.9 encoding API.
@return [Boolean]
# File lib/haml/util.rb, line 438
438: def ruby1_8?
439: # IronRuby says its version is 1.9, but doesn't support any of the encoding APIs.
440: # We have to fall back to 1.8 behavior.
441: ironruby? || (Haml::Util::RUBY_VERSION[0] == 1 && Haml::Util::RUBY_VERSION[1] < 9)
442: 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 448
448: def ruby1_8_6?
449: ruby1_8? && Haml::Util::RUBY_VERSION[2] < 7
450: 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 291
291: def silence_haml_warnings
292: old_silence_warnings = @@silence_warnings
293: @@silence_warnings = true
294: yield
295: ensure
296: @@silence_warnings = old_silence_warnings
297: 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 280
280: def silence_warnings
281: the_real_stderr, $stderr = $stderr, StringIO.new
282: yield
283: ensure
284: $stderr = the_real_stderr
285: 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 185
185: def strip_string_array(arr)
186: arr.first.lstrip! if arr.first.is_a?(String)
187: arr.last.rstrip! if arr.last.is_a?(String)
188: arr
189: 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 167
167: def substitute(ary, from, to)
168: res = ary.dup
169: i = 0
170: while i < res.size
171: if res[i...i+from.size] == from
172: res[i...i+from.size] = to
173: end
174: i += 1
175: end
176: res
177: 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 41
41: def to_hash(arr)
42: arr.compact.inject({}) {|h, (k, v)| h[k] = v; h}
43: end
Returns whether one version string represents the same or a more recent version than another.
@param v1 [String] A version string. @param v2 [String] Another version string. @return [Boolean]
# File lib/haml/util.rb, line 273
273: def version_geq(v1, v2)
274: version_gt(v1, v2) || !version_gt(v2, v1)
275: end
Returns whether one version string represents a more recent version than another.
@param v1 [String] A version string. @param v2 [String] Another version string. @return [Boolean]
# File lib/haml/util.rb, line 244
244: def version_gt(v1, v2)
245: # Construct an array to make sure the shorter version is padded with nil
246: Array.new([v1.length, v2.length].max).zip(v1.split("."), v2.split(".")) do |_, p1, p2|
247: p1 ||= "0"
248: p2 ||= "0"
249: release1 = p1 =~ /^[0-9]+$/
250: release2 = p2 =~ /^[0-9]+$/
251: if release1 && release2
252: # Integer comparison if both are full releases
253: p1, p2 = p1.to_i, p2.to_i
254: next if p1 == p2
255: return p1 > p2
256: elsif !release1 && !release2
257: # String comparison if both are prereleases
258: next if p1 == p2
259: return p1 > p2
260: else
261: # If only one is a release, that one is newer
262: return release1
263: end
264: end
265: end