Sha256: f87208b5e1ef2ff9051b425ab8b501a5552efd6ff4bc3a9cc11055c05e75137b

Contents?: true

Size: 1.31 KB

Versions: 52

Compression:

Stored size: 1.31 KB

Contents

module Hamlit
  module Concerns
    module StringInterpolation
      def string_literal(str)
        unescape_interpolation(str)
      end

      def contains_interpolation?(str)
        /#[\{$@]/ === str
      end

      private

      def unescape_interpolation(str)
        res = ''
        rest = handle_interpolation(str.inspect) do |scan|
          escapes = (scan[2].size - 1) / 2
          res << scan.matched[0...-3 - escapes]
          if escapes % 2 == 1
            res << '#{'
          else
            content = eval('"' + balance(scan, ?{, ?}, 1)[0][0...-1] + '"')
            res << '#{' + content + '}'
          end
        end
        res + rest
      end

      def handle_interpolation(str)
        scan = StringScanner.new(str)
        yield scan while scan.scan(/(.*?)(\\*)\#\{/)
        scan.rest
      end

      def balance(scanner, start, finish, count = 0)
        str = ''
        scanner = StringScanner.new(scanner) unless scanner.is_a? StringScanner
        regexp = Regexp.new("(.*?)[\\#{start.chr}\\#{finish.chr}]", Regexp::MULTILINE)
        while scanner.scan(regexp)
          str << scanner.matched
          count += 1 if scanner.matched[-1] == start
          count -= 1 if scanner.matched[-1] == finish
          return [str.strip, scanner.rest] if count == 0
        end
      end
    end
  end
end

Version data entries

52 entries across 52 versions & 1 rubygems

Version Path
hamlit-1.6.7 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.6.6 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.6.5 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.6.4 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.6.3 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.6.2 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.6.1 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.6.0 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.9 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.8 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.7 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.6 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.5 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.4 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.3 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.2 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.1 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.5.0 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.4.7 lib/hamlit/concerns/string_interpolation.rb
hamlit-1.4.6 lib/hamlit/concerns/string_interpolation.rb