Namespace

Class Index [+]

Quicksearch

Haml::Util

A module containing various useful functions.

Constants

RUBY_VERSION

An array of ints representing the Ruby version number. @api public

ENCODINGS_TO_CHECK

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

Public Instance Methods

_enc(string, encoding) click to toggle source

@private

     # File lib/haml/util.rb, line 512
512:       def _enc(string, encoding)
513:         string.encode(encoding).force_encoding("BINARY")
514:       end
ap_geq?(version) click to toggle source

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 306
306:     def ap_geq?(version)
307:       # The ActionPack module is always loaded automatically in Rails >= 3
308:       return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
309:         defined?(ActionPack::VERSION::STRING)
310: 
311:       ActionPack::VERSION::STRING >= version
312:     end
ap_geq_3?() click to toggle source

Returns whether this environment is using ActionPack version 3.0.0 or greater.

@return [Boolean]

     # File lib/haml/util.rb, line 295
295:     def ap_geq_3?
296:       ap_geq?("3.0.0.beta1")
297:     end
assert_html_safe!(text) click to toggle source

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 354
354:     def assert_html_safe!(text)
355:       return unless rails_xss_safe? && text && !text.to_s.html_safe?
356:       raise Haml::Error.new("Expected #{text.inspect} to be HTML-safe.")
357:     end
av_template_class(name) click to toggle source

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 [#] The name of the class to get.

  For example, `:Error` will return `ActionView::TemplateError`
  or `ActionView::Template::Error`.
     # File lib/haml/util.rb, line 322
322:     def av_template_class(name)
323:       return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
324:       return ActionView::Template.const_get(name.to_s)
325:     end
caller_info(entry = caller[1]) click to toggle source

Returns information about the caller of the previous method.

@param entry [String] An entry in the `#` 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 226
226:     def caller_info(entry = caller[1])
227:       info = entry.scan(/^(.*?):(-?.*?)(?::.*`(.+)')?$/).first
228:       info[1] = info[1].to_i
229:       # This is added by Rubinius to designate a block, but we don't care about it.
230:       info[2].sub!(/ \{\}\Z/, '') if info[2]
231:       info
232:     end
check_encoding(str) click to toggle source

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 407
407:     def check_encoding(str)
408:       if ruby1_8?
409:         return str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM
410:       elsif str.valid_encoding?
411:         # Get rid of the Unicode BOM if possible
412:         if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/
413:           return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '')
414:         else
415:           return str
416:         end
417:       end
418: 
419:       encoding = str.encoding
420:       newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary"))
421:       str.force_encoding("binary").split(newlines).each_with_index do |line, i|
422:         begin
423:           line.encode(encoding)
424:         rescue Encoding::UndefinedConversionError => e
425:           yield <<MSG.rstrip, i + 1
426: Invalid #{encoding.name} character #{e.error_char.dump}
427: MSG
428:         end
429:       end
430:       return str
431:     end
check_haml_encoding(str, &block) click to toggle source

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 453
453:     def check_haml_encoding(str, &block)
454:       return check_encoding(str, &block) if ruby1_8?
455:       str = str.dup if str.frozen?
456: 
457:       bom, encoding = parse_haml_magic_comment(str)
458:       if encoding; str.force_encoding(encoding)
459:       elsif bom; str.force_encoding("UTF-8")
460:       end
461: 
462:       return check_encoding(str, &block)
463:     end
check_sass_encoding(str, &block) click to toggle source

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 484
484:     def check_sass_encoding(str, &block)
485:       return check_encoding(str, &block), nil if ruby1_8?
486:       # We allow any printable ASCII characters but double quotes in the charset decl
487:       bin = str.dup.force_encoding("BINARY")
488:       encoding = Haml::Util::ENCODINGS_TO_CHECK.find do |enc|
489:         bin =~ Haml::Util::CHARSET_REGEXPS[enc]
490:       end
491:       charset, bom = $1, $2
492:       if charset
493:         charset = charset.force_encoding(encoding).encode("UTF-8")
494:         if endianness = encoding[/[BL]E$/]
495:           begin
496:             Encoding.find(charset + endianness)
497:             charset << endianness
498:           rescue ArgumentError # Encoding charset + endianness doesn't exist
499:           end
500:         end
501:         str.force_encoding(charset)
502:       elsif bom
503:         str.force_encoding(encoding)
504:       end
505: 
506:       str = check_encoding(str, &block)
507:       return str.encode("UTF-8"), str.encoding
508:     end
haml_warn(msg) click to toggle source

The same as `Kernel#warn`, but is silenced by {#silence_haml_warnings}.

@param msg [String]

     # File lib/haml/util.rb, line 259
259:     def haml_warn(msg)
260:       return if @@silence_warnings
261:       warn(msg)
262:     end
html_safe(text) click to toggle source

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 344
344:     def html_safe(text)
345:       return unless text
346:       return text.html_safe if defined?(ActiveSupport::SafeBuffer)
347:       text.html_safe!
348:     end
intersperse(enum, val) click to toggle source

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 153
153:     def intersperse(enum, val)
154:       enum.inject([]) {|a, e| a << e << val}[0...1]
155:     end
lcs(x, y, &block) click to toggle source

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 214
214:     def lcs(x, y, &block)
215:       x = [nil, *x]
216:       y = [nil, *y]
217:       block ||= proc {|a, b| a == b && a}
218:       lcs_backtrace(lcs_table(x, y, &block), x, y, x.size-1, y.size-1, &block)
219:     end
map_hash(hash, &block) click to toggle source

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 # @see #

    # File lib/haml/util.rb, line 88
88:     def map_hash(hash, &block)
89:       to_hash(hash.map(&block))
90:     end
map_keys(hash) click to toggle source

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 # @see #

    # File lib/haml/util.rb, line 53
53:     def map_keys(hash)
54:       to_hash(hash.map {|k, v| [yield(k), v]})
55:     end
map_vals(hash) click to toggle source

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 # @see #

    # File lib/haml/util.rb, line 70
70:     def map_vals(hash)
71:       to_hash(hash.map {|k, v| [k, yield(v)]})
72:     end
merge_adjacent_strings(enum) click to toggle source

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 132
132:     def merge_adjacent_strings(enum)
133:       enum.inject([]) do |a, e|
134:         if e.is_a?(String)
135:           if a.last.is_a?(String)
136:             a.last << e
137:           else
138:             a << e.dup
139:           end
140:         else
141:           a << e
142:         end
143:         a
144:       end
145:     end
paths(arrs) click to toggle source

Return an array of all possible paths through the given arrays.

@param arrs [Array] @return [Array]

@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 197
197:     def paths(arrs)
198:       arrs.inject([[]]) do |paths, arr|
199:         flatten(arr.map {|e| paths.map {|path| path + [e]}}, 1)
200:       end
201:     end
powerset(arr) click to toggle source

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] The subsets of `arr`

     # File lib/haml/util.rb, line 101
101:     def powerset(arr)
102:       arr.inject([Set.new].to_set) do |powerset, el|
103:         new_powerset = Set.new
104:         powerset.each do |subset|
105:           new_powerset << subset
106:           new_powerset << subset + [el]
107:         end
108:         new_powerset
109:       end
110:     end
rails_env() click to toggle source

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 285
285:     def rails_env
286:       return Rails.env.to_s if defined?(Rails.root)
287:       return RAILS_ENV.to_s if defined?(RAILS_ENV)
288:       return nil
289:     end
rails_root() click to toggle source

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 271
271:     def rails_root
272:       if defined?(Rails.root)
273:         return Rails.root.to_s if Rails.root
274:         raise "ERROR: Rails.root is nil!"
275:       end
276:       return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
277:       return nil
278:     end
rails_safe_buffer_class() click to toggle source

The class for the Rails SafeBuffer XSS protection class. This varies depending on Rails version.

@return [Class]

     # File lib/haml/util.rb, line 363
363:     def rails_safe_buffer_class
364:       # It's important that we check ActiveSupport first,
365:       # because in Rails 2.3.6 ActionView::SafeBuffer exists
366:       # but is a deprecated proxy object.
367:       return ActiveSupport::SafeBuffer if defined?(ActiveSupport::SafeBuffer)
368:       return ActionView::SafeBuffer
369:     end
rails_xss_safe?() click to toggle source

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 334
334:     def rails_xss_safe?
335:       false
336:     end
restrict(value, range) click to toggle source

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] @return [Numeric]

     # File lib/haml/util.rb, line 119
119:     def restrict(value, range)
120:       [[value, range.first].max, range.last].min
121:     end
ruby1_8?() click to toggle source

Whether or not this is running under Ruby 1.8 or lower.

@return [Boolean]

     # File lib/haml/util.rb, line 385
385:     def ruby1_8?
386:       Haml::Util::RUBY_VERSION[0] == 1 && Haml::Util::RUBY_VERSION[1] < 9
387:     end
ruby1_8_6?() click to toggle source

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 393
393:     def ruby1_8_6?
394:       ruby1_8? && Haml::Util::RUBY_VERSION[2] < 7
395:     end
scope(file) click to toggle source

Returns the path of a file relative to the Haml root directory.

@param file [String] The filename relative to the Haml root @return [String] The filename relative to the the working directory

    # File lib/haml/util.rb, line 24
24:     def scope(file)
25:       File.join(Haml::ROOT_DIR, file)
26:     end
silence_haml_warnings() click to toggle source

Silences all Haml warnings within a block.

@yield A block in which no Haml warnings will be printed

     # File lib/haml/util.rb, line 248
248:     def silence_haml_warnings
249:       old_silence_warnings = @@silence_warnings
250:       @@silence_warnings = true
251:       yield
252:     ensure
253:       @@silence_warnings = old_silence_warnings
254:     end
silence_warnings() click to toggle source

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 237
237:     def silence_warnings
238:       the_real_stderr, $stderr = $stderr, StringIO.new
239:       yield
240:     ensure
241:       $stderr = the_real_stderr
242:     end
strip_string_array(arr) click to toggle source

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 180
180:     def strip_string_array(arr)
181:       arr.first.lstrip! if arr.first.is_a?(String)
182:       arr.last.rstrip! if arr.last.is_a?(String)
183:       arr
184:     end
substitute(ary, from, to) click to toggle source

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 162
162:     def substitute(ary, from, to)
163:       res = ary.dup
164:       i = 0
165:       while i < res.size
166:         if res[i...i+from.size] == from
167:           res[i...i+from.size] = to
168:         end
169:         i += 1
170:       end
171:       res
172:     end
to_hash(arr) click to toggle source

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 36
36:     def to_hash(arr)
37:       arr.compact.inject({}) {|h, (k, v)| h[k] = v; h}
38:     end
windows?() click to toggle source

Whether or not this is running on Windows.

@return [Boolean]

     # File lib/haml/util.rb, line 376
376:     def windows?
377:       RbConfig::CONFIG['host_os'] =~ /mswin|windows/
378:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.