In Files

Haml::Util

A module containing various useful functions.

Constants

RUBY_VERSION

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

RUBY_ENGINE

The Ruby engine we’re running under. Defaults to `“ruby”` if the top-level constant is undefined. @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 583
583:       def _enc(string, encoding)
584:         string.encode(encoding).force_encoding("BINARY")
585:       end
abstract(obj) click to toggle source

Throws a NotImplementedError for an abstract method.

@param obj [Object] `self` @raise [NotImplementedError]

     # File lib/haml/util.rb, line 305
305:     def abstract(obj)
306:       raise NotImplementedError.new("#{obj.class} must implement ##{caller_info[2]}")
307:     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 410
410:     def ap_geq?(version)
411:       # The ActionPack module is always loaded automatically in Rails >= 3
412:       return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
413:         defined?(ActionPack::VERSION::STRING)
414: 
415:       version_geq(ActionPack::VERSION::STRING, version)
416:     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 399
399:     def ap_geq_3?
400:       ap_geq?("3.0.0.beta1")
401:     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 458
458:     def assert_html_safe!(text)
459:       return unless rails_xss_safe? && text && !text.to_s.html_safe?
460:       raise Haml::Error.new("Expected #{text.inspect} to be HTML-safe.")
461:     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 426
426:     def av_template_class(name)
427:       return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
428:       return ActionView::Template.const_get(name.to_s)
429:     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 523
523:     def check_encoding(str)
524:       if ruby1_8?
525:         return str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM
526:       elsif str.valid_encoding?
527:         # Get rid of the Unicode BOM if possible
528:         if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/
529:           return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '')
530:         else
531:           return str
532:         end
533:       end
534: 
535:       encoding = str.encoding
536:       newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary"))
537:       str.force_encoding("binary").split(newlines).each_with_index do |line, i|
538:         begin
539:           line.encode(encoding)
540:         rescue Encoding::UndefinedConversionError => e
541:           yield <<MSG.rstrip, i + 1
542: Invalid #{encoding.name} character #{e.error_char.dump}
543: MSG
544:         end
545:       end
546:       return str
547:     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 Haml 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 569
569:     def check_haml_encoding(str, &block)
570:       return check_encoding(str, &block) if ruby1_8?
571:       str = str.dup if str.frozen?
572: 
573:       bom, encoding = parse_haml_magic_comment(str)
574:       if encoding; str.force_encoding(encoding)
575:       elsif bom; str.force_encoding("UTF-8")
576:       end
577: 
578:       return check_encoding(str, &block)
579:     end
dump(obj) click to toggle source

A wrapper for `Marshal.dump` that calls `#_before_dump` on the object before dumping it, `#_after_dump` afterwards. It also calls `#_around_dump` and passes it a block in which the object is dumped.

If any of these methods are undefined, they are not called.

@param obj [Object] The object to dump. @return [String] The dumped data.

     # File lib/haml/util.rb, line 280
280:     def dump(obj)
281:       obj._before_dump if obj.respond_to?(:_before_dump)
282:       return Marshal.dump(obj) unless obj.respond_to?(:_around_dump)
283:       res = nil
284:       obj._around_dump {res = Marshal.dump(obj)}
285:       res
286:     ensure
287:       obj._after_dump if obj.respond_to?(:_after_dump)
288:     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 334
334:     def haml_warn(msg)
335:       return if @@silence_warnings
336:       warn(msg)
337:     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 448
448:     def html_safe(text)
449:       return unless text
450:       return text.html_safe if defined?(ActiveSupport::SafeBuffer)
451:       text.html_safe!
452:     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
ironruby?() click to toggle source

Whether or not this is running on IronRuby.

@return [Boolean]

     # File lib/haml/util.rb, line 487
487:     def ironruby?
488:       RUBY_ENGINE == "ironruby"
489:     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
load(data) click to toggle source

A wrapper for `Marshal.load` that calls `#_after_load` on the object after loading it, if it’s defined.

@param data [String] The data to load. @return [Object] The loaded object.

     # File lib/haml/util.rb, line 295
295:     def load(data)
296:       obj = Marshal.load(data)
297:       obj._after_load if obj.respond_to?(:_after_load)
298:       obj
299:     end
map_hash(hash, &block) click to toggle source

Maps the key-value pairs of a hash according to a block.

@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.

@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 55
55:     def map_keys(hash)
56:       to_hash(hash.map {|k, v| [yield(k), v]})
57:     end
map_vals(hash) click to toggle source

Maps the values in a hash according to a block.

@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 71
71:     def map_vals(hash)
72:       to_hash(hash.map {|k, v| [k, yield(v)]})
73:     end
merge_adjacent_strings(arr) click to toggle source

Concatenates all strings that are adjacent in an array, while leaving other elements as they are.

@example

  merge_adjacent_strings([1, "foo", "bar", 2, "baz"])
    #=> [1, "foobar", 2, "baz"]

@param arr [Array] @return [Array] The enumerable with strings merged

     # File lib/haml/util.rb, line 130
130:     def merge_adjacent_strings(arr)
131:       # Optimize for the common case of one element
132:       return arr if arr.size < 2
133:       arr.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.

@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 100
100:     def powerset(arr)
101:       arr.inject([Set.new].to_set) do |powerset, el|
102:         new_powerset = Set.new
103:         powerset.each do |subset|
104:           new_powerset << subset
105:           new_powerset << subset + [el]
106:         end
107:         new_powerset
108:       end
109:     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 389
389:     def rails_env
390:       return ::Rails.env.to_s if defined?(::Rails.env)
391:       return RAILS_ENV.to_s if defined?(RAILS_ENV)
392:       return nil
393:     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 375
375:     def rails_root
376:       if defined?(::Rails.root)
377:         return ::Rails.root.to_s if ::Rails.root
378:         raise "ERROR: Rails.root is nil!"
379:       end
380:       return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
381:       return nil
382:     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 467
467:     def rails_safe_buffer_class
468:       # It's important that we check ActiveSupport first,
469:       # because in Rails 2.3.6 ActionView::SafeBuffer exists
470:       # but is a deprecated proxy object.
471:       return ActiveSupport::SafeBuffer if defined?(ActiveSupport::SafeBuffer)
472:       return ActionView::SafeBuffer
473:     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 438
438:     def rails_xss_safe?
439:       false
440:     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 118
118:     def restrict(value, range)
119:       [[value, range.first].max, range.last].min
120:     end
ruby1_8?() click to toggle source

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 499
499:     def ruby1_8?
500:       # IronRuby says its version is 1.9, but doesn't support any of the encoding APIs.
501:       # We have to fall back to 1.8 behavior.
502:       ironruby? || (Haml::Util::RUBY_VERSION[0] == 1 && Haml::Util::RUBY_VERSION[1] < 9)
503:     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 509
509:     def ruby1_8_6?
510:       ruby1_8? && Haml::Util::RUBY_VERSION[2] < 7
511:     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 28
28:     def scope(file)
29:       File.join(Haml::ROOT_DIR, file)
30:     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 323
323:     def silence_haml_warnings
324:       old_silence_warnings = @@silence_warnings
325:       @@silence_warnings = true
326:       yield
327:     ensure
328:       @@silence_warnings = old_silence_warnings
329:     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 312
312:     def silence_warnings
313:       the_real_stderr, $stderr = $stderr, StringIO.new
314:       yield
315:     ensure
316:       $stderr = the_real_stderr
317:     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.

@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 39
39:     def to_hash(arr)
40:       Hash[arr.compact]
41:     end
try_sass() click to toggle source

Try loading Sass. If the `sass` gem isn’t installed, print a warning and load from the vendored gem.

@return [Boolean] True if Sass was successfully loaded from the `sass` gem,

  false otherwise.
     # File lib/haml/util.rb, line 344
344:     def try_sass
345:       return true if defined?(::SASS_BEGUN_TO_LOAD)
346:       begin
347:         require 'sass/version'
348:         loaded = Sass.respond_to?(:version) && Sass.version[:major] &&
349:           Sass.version[:minor] && ((Sass.version[:major] > 3 && Sass.version[:minor] > 1) ||
350:           ((Sass.version[:major] == 3 && Sass.version[:minor] == 1) &&
351:             (Sass.version[:prerelease] || Sass.version[:name] != "Bleeding Edge")))
352:       rescue LoadError => e
353:         loaded = false
354:       end
355: 
356:       unless loaded
357:         haml_warn(Sass is in the process of being separated from Haml,and will no longer be bundled at all in Haml 3.2.0.Please install the 'sass' gem if you want to use Sass.)
358:         $".delete('sass/version')
359:         $LOAD_PATH.unshift(scope("vendor/sass/lib"))
360:       end
361:       loaded
362:     end
version_geq(v1, v2) click to toggle source

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 268
268:     def version_geq(v1, v2)
269:       version_gt(v1, v2) || !version_gt(v2, v1)
270:     end
version_gt(v1, v2) click to toggle source

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 239
239:     def version_gt(v1, v2)
240:       # Construct an array to make sure the shorter version is padded with nil
241:       Array.new([v1.length, v2.length].max).zip(v1.split("."), v2.split(".")) do |_, p1, p2|
242:         p1 ||= "0"
243:         p2 ||= "0"
244:         release1 = p1 =~ /^[0-9]+$/
245:         release2 = p2 =~ /^[0-9]+$/
246:         if release1 && release2
247:           # Integer comparison if both are full releases
248:           p1, p2 = p1.to_i, p2.to_i
249:           next if p1 == p2
250:           return p1 > p2
251:         elsif !release1 && !release2
252:           # String comparison if both are prereleases
253:           next if p1 == p2
254:           return p1 > p2
255:         else
256:           # If only one is a release, that one is newer
257:           return release1
258:         end
259:       end
260:     end
windows?() click to toggle source

Whether or not this is running on Windows.

@return [Boolean]

     # File lib/haml/util.rb, line 480
480:     def windows?
481:       RbConfig::CONFIG['host_os'] =~ /mswin|windows|mingw/
482:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.