util.rb

Path: lib/haml/util.rb
Last Update: Wed Jul 28 08:11:07 +0000 2010

Required files

erb   set   enumerator   stringio   strscan   rbconfig   haml/root   haml/util/subset_map  

Methods

Public Instance methods

This is used for methods in {Haml::Buffer} that need to be very fast, and take a lot of boolean parameters that are known at compile-time. Instead of passing the parameters in normally, a separate method is defined for every possible combination of those parameters; these are then called using \{static_method_name}.

To define a static method, an ERB template for the method is provided. All conditionals based on the static parameters are done as embedded Ruby within this template. For example:

    def_static_method(Foo, :my_static_method, [:foo, :bar], :baz, :bang, <<RUBY)
      <% if baz && bang %>
        return foo + bar
      <% elsif baz || bang %>
        return foo - bar
      <% else %>
        return 17
      <% end %>
    RUBY

\{static_method_name} can be used to call static methods.

@overload def_static_method(klass, name, args, *vars, erb) @param klass [Module] The class on which to define the static method @param name [to_s] The (base) name of the static method @param args [Array<Symbol>] The names of the arguments to the defined methods

  (**not** to the ERB template)

@param vars [Array<Symbol>] The names of the static boolean variables

  to be made available to the ERB template

@param erb [String] The template for the method code

[Source]

     # File lib/haml/util.rb, line 672
672:     def def_static_method(klass, name, args, *vars)
673:       erb = vars.pop
674:       info = caller_info
675:       powerset(vars).each do |set|
676:         context = StaticConditionalContext.new(set).instance_eval {binding}
677:         klass.class_eval("def \#{static_method_name(name, *vars.map {|v| set.include?(v)})}(\#{args.join(', ')})\n  \#{ERB.new(erb).result(context)}\nend\n", info[0], info[1])
678:       end
679:     end

A version of `Enumerable#enum_cons` that works in Ruby 1.8 and 1.9.

@param enum [Enumerable] The enumerable to get the enumerator for @param n [Fixnum] The size of each cons @return [Enumerator] The consed enumerator

[Source]

     # File lib/haml/util.rb, line 568
568:     def enum_cons(enum, n)
569:       ruby1_8? ? enum.enum_cons(n) : enum.each_cons(n)
570:     end

A version of `Enumerable#enum_slice` that works in Ruby 1.8 and 1.9.

@param enum [Enumerable] The enumerable to get the enumerator for @param n [Fixnum] The size of each slice @return [Enumerator] The consed enumerator

[Source]

     # File lib/haml/util.rb, line 577
577:     def enum_slice(enum, n)
578:       ruby1_8? ? enum.enum_slice(n) : enum.each_slice(n)
579:     end

A version of `Enumerable#enum_with_index` that works in Ruby 1.8 and 1.9.

@param enum [Enumerable] The enumerable to get the enumerator for @return [Enumerator] The with-index enumerator

[Source]

     # File lib/haml/util.rb, line 559
559:     def enum_with_index(enum)
560:       ruby1_8? ? enum.enum_with_index : enum.each_with_index
561:     end

Flattens the first `n` nested arrays in a cross-version manner.

@param arr [Array] The array to flatten @param n [Fixnum] The number of levels to flatten @return [Array] The flattened array

[Source]

     # File lib/haml/util.rb, line 594
594:     def flatten(arr, n)
595:       return arr.flatten(n) unless ruby1_8_6?
596:       return arr if n == 0
597:       arr.inject([]) {|res, e| e.is_a?(Array) ? res.concat(flatten(e, n - 1)) : res << e}
598:     end

Checks to see if a class has a given method. For example:

    Haml::Util.has?(:public_instance_method, String, :gsub) #=> true

Method collections like `Class#instance_methods` return strings in Ruby 1.8 and symbols in Ruby 1.9 and on, so this handles checking for them in a compatible way.

@param attr [to_s] The (singular) name of the method-collection method

  (e.g. `:instance_methods`, `:private_methods`)

@param klass [Module] The class to check the methods of which to check @param method [String, Symbol] The name of the method do check for @return [Boolean] Whether or not the given collection has the given method

[Source]

     # File lib/haml/util.rb, line 551
551:     def has?(attr, klass, method)
552:       klass.send("#{attr}s").include?(ruby1_8? ? method.to_s : method.to_sym)
553:     end

Returns the ASCII code of the given character.

@param c [String] All characters but the first are ignored. @return [Fixnum] The ASCII code of `c`.

[Source]

     # File lib/haml/util.rb, line 585
585:     def ord(c)
586:       ruby1_8? ? c[0] : c.ord
587:     end

Tests the hash-equality of two sets in a cross-version manner. Aggravatingly, this is order-dependent in Ruby 1.8.6.

@param set1 [Set] @param set2 [Set] @return [Boolean] Whether or not the sets are hashcode equal

[Source]

     # File lib/haml/util.rb, line 616
616:     def set_eql?(set1, set2)
617:       return set1.eql?(set2) unless ruby1_8_6?
618:       set1.to_a.uniq.sort_by {|e| e.hash}.eql?(set2.to_a.uniq.sort_by {|e| e.hash})
619:     end

Returns the hash code for a set in a cross-version manner. Aggravatingly, this is order-dependent in Ruby 1.8.6.

@param set [Set] @return [Fixnum] The order-independent hashcode of `set`

[Source]

     # File lib/haml/util.rb, line 605
605:     def set_hash(set)
606:       return set.hash unless ruby1_8_6?
607:       set.map {|e| e.hash}.uniq.sort.hash
608:     end

Computes the name for a method defined via \{def_static_method}.

@param name [String] The base name of the static method @param vars [Array<Boolean>] The static variable assignment @return [String] The real name of the static method

[Source]

     # File lib/haml/util.rb, line 691
691:     def static_method_name(name, *vars)
692:       "#{name}_#{vars.map {|v| !!v}.join('_')}"
693:     end

Private Instance methods

Computes a single longest common subsequence for arrays x and y. Algorithm from [Wikipedia](en.wikipedia.org/wiki/Longest_common_subsequence_problem#Reading_out_an_LCS)

[Source]

     # File lib/haml/util.rb, line 718
718:     def lcs_backtrace(c, x, y, i, j, &block)
719:       return [] if i == 0 || j == 0
720:       if v = yield(x[i], y[j])
721:         return lcs_backtrace(c, x, y, i-1, j-1, &block) << v
722:       end
723: 
724:       return lcs_backtrace(c, x, y, i, j-1, &block) if c[i][j-1] > c[i-1][j]
725:       return lcs_backtrace(c, x, y, i-1, j, &block)
726:     end

Calculates the memoization table for the Least Common Subsequence algorithm. Algorithm from [Wikipedia](en.wikipedia.org/wiki/Longest_common_subsequence_problem#Computing_the_length_of_the_LCS)

[Source]

     # File lib/haml/util.rb, line 699
699:     def lcs_table(x, y)
700:       c = Array.new(x.size) {[]}
701:       x.size.times {|i| c[i][0] = 0}
702:       y.size.times {|j| c[0][j] = 0}
703:       (1...x.size).each do |i|
704:         (1...y.size).each do |j|
705:           c[i][j] =
706:             if yield x[i], y[j]
707:               c[i-1][j-1] + 1
708:             else
709:               [c[i][j-1], c[i-1][j]].max
710:             end
711:         end
712:       end
713:       return c
714:     end

Parses a magic comment at the beginning of a Haml file. The parsing rules are basically the same as Ruby‘s.

@return [(Boolean, String or nil)]

  Whether the document begins with a UTF-8 BOM,
  and the declared encoding of the document (or nil if none is declared)

[Source]

     # File lib/haml/util.rb, line 734
734:     def parse_haml_magic_comment(str)
735:       scanner = StringScanner.new(str.dup.force_encoding("BINARY"))
736:       bom = scanner.scan(/\xEF\xBB\xBF/n)
737:       return bom unless scanner.scan(/-\s*#\s*/n)
738:       if coding = try_parse_haml_emacs_magic_comment(scanner)
739:         return bom, coding
740:       end
741: 
742:       return bom unless scanner.scan(/.*?coding[=:]\s*([\w-]+)/in)
743:       return bom, scanner[1]
744:     end

[Source]

     # File lib/haml/util.rb, line 746
746:     def try_parse_haml_emacs_magic_comment(scanner)
747:       pos = scanner.pos
748:       return unless scanner.scan(/.*?-\*-\s*/n)
749:       # From Ruby's parse.y
750:       return unless scanner.scan(/([^\s'":;]+)\s*:\s*("(?:\\.|[^"])*"|[^"\s;]+?)[\s;]*-\*-/n)
751:       name, val = scanner[1], scanner[2]
752:       return unless name =~ /(en)?coding/in
753:       val = $1 if val =~ /^"(.*)"$/n
754:       return val
755:     ensure
756:       scanner.pos = pos
757:     end

[Validate]