Module: MojiBake::JSONSupport

Includes:
VersionSupport
Included in:
Mapper
Defined in:
lib/mojibake/json.rb

Constant Summary collapse

JSON_CONFIG =
File.join( File.dirname( __FILE__ ),
'..', '..', 'config', 'table.json' )

Instance Method Summary collapse

Methods included from VersionSupport

#jruby_version_a, #ruby_version_a, #ver_to_a

Instance Method Details

#configObject



32
33
34
# File 'lib/mojibake/json.rb', line 32

def config
  @config ||= JSON.parse( IO.read( JSON_CONFIG ) )
end

#create_regexpObject



44
45
46
47
48
# File 'lib/mojibake/json.rb', line 44

def create_regexp
  # Use (U)nicode mode on ruby 1.8 only
  lang = ( ruby_version_a <=> [1,9] ) >= 0 ? nil : 'U'
  Regexp.new( config[ 'regexp' ], 0, lang )
end

#hashObject



36
37
38
# File 'lib/mojibake/json.rb', line 36

def hash
  @hash ||= config[ 'moji' ]
end

#hash_to_json_objectObject

table as self contained json-ready Hash



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/mojibake/json.rb', line 51

def hash_to_json_object

  # Also use unicode escape for the interesting (effectively,
  # non-printable) subset of moji mappings.
  moji = hash.sort.map do |kv|
    kv.map do |s|
      s.codepoints.inject( '' ) do |r,i|
        if MojiBake::Mapper::INTEREST_CODEPOINTS.include?( i )
          r << sprintf( '\u%04X', i )
        else
          r << i.chr( Encoding::UTF_8 )
        end
      end
    end
  end

  { :mojibake => MojiBake::VERSION,
    :url => "https://github.com/dekellum/mojibake",
    :regexp => regexp.inspect[1...-1],
    :moji =>  Hash[ moji ] }
end

#initializeObject



28
29
30
# File 'lib/mojibake/json.rb', line 28

def initialize
  super
end

#jsonObject

Pretty formatted JSON serialized String for json_object



74
75
76
77
78
79
80
81
82
83
# File 'lib/mojibake/json.rb', line 74

def json
  # Generate and replace what become double escaped '\\u' UNICODE
  # escapes with single '\u' escapes. This is a hack but is
  # reasonably safe given that 'u' isn't normally escaped.  The
  # alterantive would be to hack JSON package or do the JSON
  # formatting ourselves.  Ideally JSON package would support
  # serialization using unicode escapes for the non-printable,
  # non-friendly chars. As of 1.6.1 it doesn't.
  JSON.pretty_generate( hash_to_json_object ).gsub( /\\\\u/, '\u' )
end

#regexpObject



40
41
42
# File 'lib/mojibake/json.rb', line 40

def regexp
  @regexp ||= create_regexp
end