File: string_dumper.rb

package info (click to toggle)
ruby-kdl 1.0.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 480 kB
  • sloc: ruby: 6,667; yacc: 72; sh: 5; makefile: 4
file content (45 lines) | stat: -rw-r--r-- 999 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module KDL
  module StringDumper
    class << self
      def call(string)
        %("#{string.each_char.map { |char| escape(char) }.join}")
      end

      def stringify_identifier(ident)
        if bare_identifier?(ident)
          ident
        else
          call(ident)
        end
      end

      private

      def print?(char)
        ' ' <= char && char <= '\x7e'
      end

      def escape(char)
        case char
        when "\n" then '\n'
        when "\r" then '\r'
        when "\t" then '\t'
        when '\\' then '\\\\'
        when '"' then '\"'
        when "\b" then '\b'
        when "\f" then '\f'
        else char
        end
      end

      def unicode_escape(char)
        "\\u{#{char.codepoints.first.to_s(16)}}"
      end

      def bare_identifier?(name)
        escape_chars = '\\\/(){}<>;\[\]=,"'
        name =~ /^([^0-9\-+\s#{escape_chars}][^\s#{escape_chars}]*|[\-+](?!true|false|null)[^0-9\s#{escape_chars}][^\s#{escape_chars}]*)$/
      end
    end
  end
end