ghi 1.1.1 → 1.2.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 1828848134ca1f5fa1a6179446c28f99671c5a96
4
- data.tar.gz: c9c4798f691902708e67f9b7695a4845ed95c106
3
+ metadata.gz: cf60dfd0d186793f1f58e67aaf6e02c15099eb6a
4
+ data.tar.gz: f159c9cb960dc248c8dcdfef7efe827089257275
5
5
  SHA512:
6
- metadata.gz: 3e1c7b6abb8f1657e6bb65cdc132902906d96456d2d97ed5efc114c3607d46277f5d431c16f9961c61fd216d8999488501605295bcf9a5edd74b02d47c959428
7
- data.tar.gz: 7a804131fe86e958b11066fe6d0773b52d44236cc30223d0dd6b8589252db1eeb96bae40ec7dd5fb782c668b0c87d75084097f9221f322e3eb0699f1c810a821
6
+ metadata.gz: 0b0b760af55aec8b781b40932dd08d65122d2c2db8b5a73aabf83dbe82273c80a8c3a8fed1fdcbe24458f682dfa6d67ed55f08024de060d0176902117cf12c0b
7
+ data.tar.gz: 62776a3dfc2adbac46b59eff82181027e57355dd38ff9d79c6a7a732334855a415d61bc9898ebfec187b68f320f7f5525108e1e01ea770204c601439b9624864
@@ -1,5 +1,6 @@
1
1
  require 'cgi'
2
2
  require 'net/https'
3
+ require 'json'
3
4
 
4
5
  unless defined? Net::HTTP::Patch
5
6
  # PATCH support for 1.8.7.
@@ -8,7 +9,6 @@ end
8
9
 
9
10
  module GHI
10
11
  class Client
11
- autoload :JSON, 'ghi/json'
12
12
 
13
13
  class Error < RuntimeError
14
14
  attr_reader :response
@@ -33,6 +33,11 @@ module GHI
33
33
  ) do |labels|
34
34
  (assigns[:exclude_labels] ||= []).concat labels
35
35
  end
36
+ opts.on(
37
+ '--no-labels', 'do not print labels'
38
+ ) do
39
+ assigns[:dont_print_labels] = true
40
+ end
36
41
  opts.on(
37
42
  '-S', '--sort <by>', %w(created updated comments),
38
43
  {'c'=>'created','u'=>'updated','m'=>'comments'},
@@ -2,8 +2,8 @@ module GHI
2
2
  module Commands
3
3
  module Version
4
4
  MAJOR = 1
5
- MINOR = 1
6
- PATCH = 1
5
+ MINOR = 2
6
+ PATCH = 0
7
7
  PRE = nil
8
8
 
9
9
  VERSION = [MAJOR, MINOR, PATCH, PRE].compact.join '.'
@@ -193,7 +193,7 @@ module GHI
193
193
  (i['repo'].to_s.rjust(rmax) if i['repo']),
194
194
  format_number(n.to_s.rjust(nmax)),
195
195
  truncate(title, l),
196
- format_labels(labels),
196
+ (format_labels(labels) unless assigns[:dont_print_labels]),
197
197
  (fg(:green) { m['title'] } if m),
198
198
  (fg('aaaaaa') { c } unless c == 0),
199
199
  (fg('aaaaaa') { '↑' } if p),
@@ -413,8 +413,8 @@ EOF
413
413
  def format_comment_editor issue, comment = nil
414
414
  message = ERB.new(<<EOF).result binding
415
415
 
416
- Leave a comment. Trailing lines starting with '#' (like these) will be ignored,
417
- and empty messages will not be submitted. Comments are formatted with GitHub
416
+ Leave a comment. Trailing lines starting with '#' (like these) will be ignored,
417
+ and empty messages will not be submitted. Comments are formatted with GitHub
418
418
  Flavored Markdown (GFM):
419
419
 
420
420
  http://github.github.com/github-flavored-markdown
@@ -309,7 +309,7 @@ module GHI
309
309
  raise unless supports_256_colors?
310
310
  require 'pygments'
311
311
  Pygmentizer.new
312
- rescue
312
+ rescue StandardError, LoadError
313
313
  FakePygmentizer.new
314
314
  end
315
315
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ghi
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.1.1
4
+ version: 1.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Stephen Celis
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2016-02-26 00:00:00.000000000 Z
11
+ date: 2016-04-20 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: pygments.rb
@@ -84,7 +84,6 @@ files:
84
84
  - lib/ghi/editor.rb
85
85
  - lib/ghi/formatting.rb
86
86
  - lib/ghi/formatting/colors.rb
87
- - lib/ghi/json.rb
88
87
  - lib/ghi/web.rb
89
88
  homepage: https://github.com/stephencelis/ghi
90
89
  licenses:
@@ -1,1306 +0,0 @@
1
- unless defined? JSON
2
- require 'strscan'
3
-
4
- module JSON
5
- module Pure
6
- # This class implements the JSON parser that is used to parse a JSON string
7
- # into a Ruby data structure.
8
- class Parser < StringScanner
9
- STRING = /" ((?:[^\x0-\x1f"\\] |
10
- # escaped special characters:
11
- \\["\\\/bfnrt] |
12
- \\u[0-9a-fA-F]{4} |
13
- # match all but escaped special characters:
14
- \\[\x20-\x21\x23-\x2e\x30-\x5b\x5d-\x61\x63-\x65\x67-\x6d\x6f-\x71\x73\x75-\xff])*)
15
- "/nx
16
- INTEGER = /(-?0|-?[1-9]\d*)/
17
- FLOAT = /(-?
18
- (?:0|[1-9]\d*)
19
- (?:
20
- \.\d+(?i:e[+-]?\d+) |
21
- \.\d+ |
22
- (?i:e[+-]?\d+)
23
- )
24
- )/x
25
- NAN = /NaN/
26
- INFINITY = /Infinity/
27
- MINUS_INFINITY = /-Infinity/
28
- OBJECT_OPEN = /\{/
29
- OBJECT_CLOSE = /\}/
30
- ARRAY_OPEN = /\[/
31
- ARRAY_CLOSE = /\]/
32
- PAIR_DELIMITER = /:/
33
- COLLECTION_DELIMITER = /,/
34
- TRUE = /true/
35
- FALSE = /false/
36
- NULL = /null/
37
- IGNORE = %r(
38
- (?:
39
- //[^\n\r]*[\n\r]| # line comments
40
- /\* # c-style comments
41
- (?:
42
- [^*/]| # normal chars
43
- /[^*]| # slashes that do not start a nested comment
44
- \*[^/]| # asterisks that do not end this comment
45
- /(?=\*/) # single slash before this comment's end
46
- )*
47
- \*/ # the End of this comment
48
- |[ \t\r\n]+ # whitespaces: space, horicontal tab, lf, cr
49
- )+
50
- )mx
51
-
52
- UNPARSED = Object.new
53
-
54
- # Creates a new JSON::Pure::Parser instance for the string _source_.
55
- #
56
- # It will be configured by the _opts_ hash. _opts_ can have the following
57
- # keys:
58
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
59
- # structures. Disable depth checking with :max_nesting => false|nil|0,
60
- # it defaults to 19.
61
- # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
62
- # defiance of RFC 4627 to be parsed by the Parser. This option defaults
63
- # to false.
64
- # * *symbolize_names*: If set to true, returns symbols for the names
65
- # (keys) in a JSON object. Otherwise strings are returned, which is also
66
- # the default.
67
- # * *create_additions*: If set to false, the Parser doesn't create
68
- # additions even if a matchin class and create_id was found. This option
69
- # defaults to true.
70
- # * *object_class*: Defaults to Hash
71
- # * *array_class*: Defaults to Array
72
- # * *quirks_mode*: Enables quirks_mode for parser, that is for example
73
- # parsing single JSON values instead of documents is possible.
74
- def initialize(source, opts = {})
75
- opts ||= {}
76
- unless @quirks_mode = opts[:quirks_mode]
77
- source = convert_encoding source
78
- end
79
- super source
80
- if !opts.key?(:max_nesting) # defaults to 19
81
- @max_nesting = 19
82
- elsif opts[:max_nesting]
83
- @max_nesting = opts[:max_nesting]
84
- else
85
- @max_nesting = 0
86
- end
87
- @allow_nan = !!opts[:allow_nan]
88
- @symbolize_names = !!opts[:symbolize_names]
89
- if opts.key?(:create_additions)
90
- @create_additions = !!opts[:create_additions]
91
- else
92
- @create_additions = true
93
- end
94
- @create_id = @create_additions ? JSON.create_id : nil
95
- @object_class = opts[:object_class] || Hash
96
- @array_class = opts[:array_class] || Array
97
- @match_string = opts[:match_string]
98
- end
99
-
100
- alias source string
101
-
102
- def quirks_mode?
103
- !!@quirks_mode
104
- end
105
-
106
- def reset
107
- super
108
- @current_nesting = 0
109
- end
110
-
111
- # Parses the current JSON string _source_ and returns the complete data
112
- # structure as a result.
113
- def parse
114
- reset
115
- obj = nil
116
- if @quirks_mode
117
- while !eos? && skip(IGNORE)
118
- end
119
- if eos?
120
- raise ParserError, "source did not contain any JSON!"
121
- else
122
- obj = parse_value
123
- obj == UNPARSED and raise ParserError, "source did not contain any JSON!"
124
- end
125
- else
126
- until eos?
127
- case
128
- when scan(OBJECT_OPEN)
129
- obj and raise ParserError, "source '#{peek(20)}' not in JSON!"
130
- @current_nesting = 1
131
- obj = parse_object
132
- when scan(ARRAY_OPEN)
133
- obj and raise ParserError, "source '#{peek(20)}' not in JSON!"
134
- @current_nesting = 1
135
- obj = parse_array
136
- when skip(IGNORE)
137
- ;
138
- else
139
- raise ParserError, "source '#{peek(20)}' not in JSON!"
140
- end
141
- end
142
- obj or raise ParserError, "source did not contain any JSON!"
143
- end
144
- obj
145
- end
146
-
147
- private
148
-
149
- def convert_encoding(source)
150
- if source.respond_to?(:to_str)
151
- source = source.to_str
152
- else
153
- raise TypeError, "#{source.inspect} is not like a string"
154
- end
155
- if defined?(::Encoding)
156
- if source.encoding == ::Encoding::ASCII_8BIT
157
- b = source[0, 4].bytes.to_a
158
- source =
159
- case
160
- when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0
161
- source.dup.force_encoding(::Encoding::UTF_32BE).encode!(::Encoding::UTF_8)
162
- when b.size >= 4 && b[0] == 0 && b[2] == 0
163
- source.dup.force_encoding(::Encoding::UTF_16BE).encode!(::Encoding::UTF_8)
164
- when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0
165
- source.dup.force_encoding(::Encoding::UTF_32LE).encode!(::Encoding::UTF_8)
166
- when b.size >= 4 && b[1] == 0 && b[3] == 0
167
- source.dup.force_encoding(::Encoding::UTF_16LE).encode!(::Encoding::UTF_8)
168
- else
169
- source.dup
170
- end
171
- else
172
- source = source.encode(::Encoding::UTF_8)
173
- end
174
- source.force_encoding(::Encoding::ASCII_8BIT)
175
- else
176
- b = source
177
- source =
178
- case
179
- when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0
180
- JSON.iconv('utf-8', 'utf-32be', b)
181
- when b.size >= 4 && b[0] == 0 && b[2] == 0
182
- JSON.iconv('utf-8', 'utf-16be', b)
183
- when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0
184
- JSON.iconv('utf-8', 'utf-32le', b)
185
- when b.size >= 4 && b[1] == 0 && b[3] == 0
186
- JSON.iconv('utf-8', 'utf-16le', b)
187
- else
188
- b
189
- end
190
- end
191
- source
192
- end
193
-
194
- # Unescape characters in strings.
195
- UNESCAPE_MAP = Hash.new { |h, k| h[k] = k.chr }
196
- UNESCAPE_MAP.update({
197
- ?" => '"',
198
- ?\\ => '\\',
199
- ?/ => '/',
200
- ?b => "\b",
201
- ?f => "\f",
202
- ?n => "\n",
203
- ?r => "\r",
204
- ?t => "\t",
205
- ?u => nil,
206
- })
207
-
208
- EMPTY_8BIT_STRING = ''
209
- if ::String.method_defined?(:encode)
210
- EMPTY_8BIT_STRING.force_encoding Encoding::ASCII_8BIT
211
- end
212
-
213
- def parse_string
214
- if scan(STRING)
215
- return '' if self[1].empty?
216
- string = self[1].gsub(%r((?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff]))n) do |c|
217
- if u = UNESCAPE_MAP[$&[1]]
218
- u
219
- else # \uXXXX
220
- bytes = EMPTY_8BIT_STRING.dup
221
- i = 0
222
- while c[6 * i] == ?\\ && c[6 * i + 1] == ?u
223
- bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16)
224
- i += 1
225
- end
226
- JSON.iconv('utf-8', 'utf-16be', bytes)
227
- end
228
- end
229
- if string.respond_to?(:force_encoding)
230
- string.force_encoding(::Encoding::UTF_8)
231
- end
232
- if @create_additions and @match_string
233
- for (regexp, klass) in @match_string
234
- klass.json_creatable? or next
235
- string =~ regexp and return klass.json_create(string)
236
- end
237
- end
238
- string
239
- else
240
- UNPARSED
241
- end
242
- rescue => e
243
- raise ParserError, "Caught #{e.class} at '#{peek(20)}': #{e}"
244
- end
245
-
246
- def parse_value
247
- case
248
- when scan(FLOAT)
249
- Float(self[1])
250
- when scan(INTEGER)
251
- Integer(self[1])
252
- when scan(TRUE)
253
- true
254
- when scan(FALSE)
255
- false
256
- when scan(NULL)
257
- nil
258
- when (string = parse_string) != UNPARSED
259
- string
260
- when scan(ARRAY_OPEN)
261
- @current_nesting += 1
262
- ary = parse_array
263
- @current_nesting -= 1
264
- ary
265
- when scan(OBJECT_OPEN)
266
- @current_nesting += 1
267
- obj = parse_object
268
- @current_nesting -= 1
269
- obj
270
- when @allow_nan && scan(NAN)
271
- NaN
272
- when @allow_nan && scan(INFINITY)
273
- Infinity
274
- when @allow_nan && scan(MINUS_INFINITY)
275
- MinusInfinity
276
- else
277
- UNPARSED
278
- end
279
- end
280
-
281
- def parse_array
282
- raise NestingError, "nesting of #@current_nesting is too deep" if
283
- @max_nesting.nonzero? && @current_nesting > @max_nesting
284
- result = @array_class.new
285
- delim = false
286
- until eos?
287
- case
288
- when (value = parse_value) != UNPARSED
289
- delim = false
290
- result << value
291
- skip(IGNORE)
292
- if scan(COLLECTION_DELIMITER)
293
- delim = true
294
- elsif match?(ARRAY_CLOSE)
295
- ;
296
- else
297
- raise ParserError, "expected ',' or ']' in array at '#{peek(20)}'!"
298
- end
299
- when scan(ARRAY_CLOSE)
300
- if delim
301
- raise ParserError, "expected next element in array at '#{peek(20)}'!"
302
- end
303
- break
304
- when skip(IGNORE)
305
- ;
306
- else
307
- raise ParserError, "unexpected token in array at '#{peek(20)}'!"
308
- end
309
- end
310
- result
311
- end
312
-
313
- def parse_object
314
- raise NestingError, "nesting of #@current_nesting is too deep" if
315
- @max_nesting.nonzero? && @current_nesting > @max_nesting
316
- result = @object_class.new
317
- delim = false
318
- until eos?
319
- case
320
- when (string = parse_string) != UNPARSED
321
- skip(IGNORE)
322
- unless scan(PAIR_DELIMITER)
323
- raise ParserError, "expected ':' in object at '#{peek(20)}'!"
324
- end
325
- skip(IGNORE)
326
- unless (value = parse_value).equal? UNPARSED
327
- result[@symbolize_names ? string.to_sym : string] = value
328
- delim = false
329
- skip(IGNORE)
330
- if scan(COLLECTION_DELIMITER)
331
- delim = true
332
- elsif match?(OBJECT_CLOSE)
333
- ;
334
- else
335
- raise ParserError, "expected ',' or '}' in object at '#{peek(20)}'!"
336
- end
337
- else
338
- raise ParserError, "expected value in object at '#{peek(20)}'!"
339
- end
340
- when scan(OBJECT_CLOSE)
341
- if delim
342
- raise ParserError, "expected next name, value pair in object at '#{peek(20)}'!"
343
- end
344
- if @create_additions and klassname = result[@create_id]
345
- klass = JSON.deep_const_get klassname
346
- break unless klass and klass.json_creatable?
347
- result = klass.json_create(result)
348
- end
349
- break
350
- when skip(IGNORE)
351
- ;
352
- else
353
- raise ParserError, "unexpected token in object at '#{peek(20)}'!"
354
- end
355
- end
356
- result
357
- end
358
- end
359
- end
360
- end
361
-
362
- module JSON
363
- MAP = {
364
- "\x0" => '\u0000',
365
- "\x1" => '\u0001',
366
- "\x2" => '\u0002',
367
- "\x3" => '\u0003',
368
- "\x4" => '\u0004',
369
- "\x5" => '\u0005',
370
- "\x6" => '\u0006',
371
- "\x7" => '\u0007',
372
- "\b" => '\b',
373
- "\t" => '\t',
374
- "\n" => '\n',
375
- "\xb" => '\u000b',
376
- "\f" => '\f',
377
- "\r" => '\r',
378
- "\xe" => '\u000e',
379
- "\xf" => '\u000f',
380
- "\x10" => '\u0010',
381
- "\x11" => '\u0011',
382
- "\x12" => '\u0012',
383
- "\x13" => '\u0013',
384
- "\x14" => '\u0014',
385
- "\x15" => '\u0015',
386
- "\x16" => '\u0016',
387
- "\x17" => '\u0017',
388
- "\x18" => '\u0018',
389
- "\x19" => '\u0019',
390
- "\x1a" => '\u001a',
391
- "\x1b" => '\u001b',
392
- "\x1c" => '\u001c',
393
- "\x1d" => '\u001d',
394
- "\x1e" => '\u001e',
395
- "\x1f" => '\u001f',
396
- '"' => '\"',
397
- '\\' => '\\\\',
398
- } # :nodoc:
399
-
400
- # Convert a UTF8 encoded Ruby string _string_ to a JSON string, encoded with
401
- # UTF16 big endian characters as \u????, and return it.
402
- if defined?(::Encoding)
403
- def utf8_to_json(string) # :nodoc:
404
- string = string.dup
405
- string << '' # XXX workaround: avoid buffer sharing
406
- string.force_encoding(::Encoding::ASCII_8BIT)
407
- string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] }
408
- string.force_encoding(::Encoding::UTF_8)
409
- string
410
- end
411
-
412
- def utf8_to_json_ascii(string) # :nodoc:
413
- string = string.dup
414
- string << '' # XXX workaround: avoid buffer sharing
415
- string.force_encoding(::Encoding::ASCII_8BIT)
416
- string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] }
417
- string.gsub!(/(
418
- (?:
419
- [\xc2-\xdf][\x80-\xbf] |
420
- [\xe0-\xef][\x80-\xbf]{2} |
421
- [\xf0-\xf4][\x80-\xbf]{3}
422
- )+ |
423
- [\x80-\xc1\xf5-\xff] # invalid
424
- )/nx) { |c|
425
- c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
426
- s = JSON.iconv('utf-16be', 'utf-8', c).unpack('H*')[0]
427
- s.gsub!(/.{4}/n, '\\\\u\&')
428
- }
429
- string.force_encoding(::Encoding::UTF_8)
430
- string
431
- rescue => e
432
- raise GeneratorError, "Caught #{e.class}: #{e}"
433
- end
434
- else
435
- def utf8_to_json(string) # :nodoc:
436
- string.gsub(/["\\\x0-\x1f]/) { MAP[$&] }
437
- end
438
-
439
- def utf8_to_json_ascii(string) # :nodoc:
440
- string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] }
441
- string.gsub!(/(
442
- (?:
443
- [\xc2-\xdf][\x80-\xbf] |
444
- [\xe0-\xef][\x80-\xbf]{2} |
445
- [\xf0-\xf4][\x80-\xbf]{3}
446
- )+ |
447
- [\x80-\xc1\xf5-\xff] # invalid
448
- )/nx) { |c|
449
- c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
450
- s = JSON.iconv('utf-16be', 'utf-8', c).unpack('H*')[0]
451
- s.gsub!(/.{4}/n, '\\\\u\&')
452
- }
453
- string
454
- rescue => e
455
- raise GeneratorError, "Caught #{e.class}: #{e}"
456
- end
457
- end
458
- module_function :utf8_to_json, :utf8_to_json_ascii
459
-
460
- module Pure
461
- module Generator
462
- # This class is used to create State instances, that are use to hold data
463
- # while generating a JSON text from a Ruby data structure.
464
- class State
465
- # Creates a State object from _opts_, which ought to be Hash to create
466
- # a new State instance configured by _opts_, something else to create
467
- # an unconfigured instance. If _opts_ is a State object, it is just
468
- # returned.
469
- def self.from_state(opts)
470
- case
471
- when self === opts
472
- opts
473
- when opts.respond_to?(:to_hash)
474
- new(opts.to_hash)
475
- when opts.respond_to?(:to_h)
476
- new(opts.to_h)
477
- else
478
- SAFE_STATE_PROTOTYPE.dup
479
- end
480
- end
481
-
482
- # Instantiates a new State object, configured by _opts_.
483
- #
484
- # _opts_ can have the following keys:
485
- #
486
- # * *indent*: a string used to indent levels (default: ''),
487
- # * *space*: a string that is put after, a : or , delimiter (default: ''),
488
- # * *space_before*: a string that is put before a : pair delimiter (default: ''),
489
- # * *object_nl*: a string that is put at the end of a JSON object (default: ''),
490
- # * *array_nl*: a string that is put at the end of a JSON array (default: ''),
491
- # * *check_circular*: is deprecated now, use the :max_nesting option instead,
492
- # * *max_nesting*: sets the maximum level of data structure nesting in
493
- # the generated JSON, max_nesting = 0 if no maximum should be checked.
494
- # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
495
- # generated, otherwise an exception is thrown, if these values are
496
- # encountered. This options defaults to false.
497
- # * *quirks_mode*: Enables quirks_mode for parser, that is for example
498
- # generating single JSON values instead of documents is possible.
499
- def initialize(opts = {})
500
- @indent = ''
501
- @space = ''
502
- @space_before = ''
503
- @object_nl = ''
504
- @array_nl = ''
505
- @allow_nan = false
506
- @ascii_only = false
507
- @quirks_mode = false
508
- @buffer_initial_length = 1024
509
- configure opts
510
- end
511
-
512
- # This string is used to indent levels in the JSON text.
513
- attr_accessor :indent
514
-
515
- # This string is used to insert a space between the tokens in a JSON
516
- # string.
517
- attr_accessor :space
518
-
519
- # This string is used to insert a space before the ':' in JSON objects.
520
- attr_accessor :space_before
521
-
522
- # This string is put at the end of a line that holds a JSON object (or
523
- # Hash).
524
- attr_accessor :object_nl
525
-
526
- # This string is put at the end of a line that holds a JSON array.
527
- attr_accessor :array_nl
528
-
529
- # This integer returns the maximum level of data structure nesting in
530
- # the generated JSON, max_nesting = 0 if no maximum is checked.
531
- attr_accessor :max_nesting
532
-
533
- # If this attribute is set to true, quirks mode is enabled, otherwise
534
- # it's disabled.
535
- attr_accessor :quirks_mode
536
-
537
- # :stopdoc:
538
- attr_reader :buffer_initial_length
539
-
540
- def buffer_initial_length=(length)
541
- if length > 0
542
- @buffer_initial_length = length
543
- end
544
- end
545
- # :startdoc:
546
-
547
- # This integer returns the current depth data structure nesting in the
548
- # generated JSON.
549
- attr_accessor :depth
550
-
551
- def check_max_nesting # :nodoc:
552
- return if @max_nesting.zero?
553
- current_nesting = depth + 1
554
- current_nesting > @max_nesting and
555
- raise NestingError, "nesting of #{current_nesting} is too deep"
556
- end
557
-
558
- # Returns true, if circular data structures are checked,
559
- # otherwise returns false.
560
- def check_circular?
561
- !@max_nesting.zero?
562
- end
563
-
564
- # Returns true if NaN, Infinity, and -Infinity should be considered as
565
- # valid JSON and output.
566
- def allow_nan?
567
- @allow_nan
568
- end
569
-
570
- # Returns true, if only ASCII characters should be generated. Otherwise
571
- # returns false.
572
- def ascii_only?
573
- @ascii_only
574
- end
575
-
576
- # Returns true, if quirks mode is enabled. Otherwise returns false.
577
- def quirks_mode?
578
- @quirks_mode
579
- end
580
-
581
- # Configure this State instance with the Hash _opts_, and return
582
- # itself.
583
- def configure(opts)
584
- @indent = opts[:indent] if opts.key?(:indent)
585
- @space = opts[:space] if opts.key?(:space)
586
- @space_before = opts[:space_before] if opts.key?(:space_before)
587
- @object_nl = opts[:object_nl] if opts.key?(:object_nl)
588
- @array_nl = opts[:array_nl] if opts.key?(:array_nl)
589
- @allow_nan = !!opts[:allow_nan] if opts.key?(:allow_nan)
590
- @ascii_only = opts[:ascii_only] if opts.key?(:ascii_only)
591
- @depth = opts[:depth] || 0
592
- @quirks_mode = opts[:quirks_mode] if opts.key?(:quirks_mode)
593
- if !opts.key?(:max_nesting) # defaults to 19
594
- @max_nesting = 19
595
- elsif opts[:max_nesting]
596
- @max_nesting = opts[:max_nesting]
597
- else
598
- @max_nesting = 0
599
- end
600
- self
601
- end
602
- alias merge configure
603
-
604
- # Returns the configuration instance variables as a hash, that can be
605
- # passed to the configure method.
606
- def to_h
607
- result = {}
608
- for iv in %w[indent space space_before object_nl array_nl allow_nan max_nesting ascii_only quirks_mode buffer_initial_length depth]
609
- result[iv.intern] = instance_variable_get("@#{iv}")
610
- end
611
- result
612
- end
613
-
614
- # Generates a valid JSON document from object +obj+ and returns the
615
- # result. If no valid JSON document can be created this method raises a
616
- # GeneratorError exception.
617
- def generate(obj)
618
- result = obj.to_json(self)
619
- unless @quirks_mode
620
- unless result =~ /\A\s*\[/ && result =~ /\]\s*\Z/ ||
621
- result =~ /\A\s*\{/ && result =~ /\}\s*\Z/
622
- then
623
- raise GeneratorError, "only generation of JSON objects or arrays allowed"
624
- end
625
- end
626
- result
627
- end
628
-
629
- # Return the value returned by method +name+.
630
- def [](name)
631
- __send__ name
632
- end
633
- end
634
-
635
- module GeneratorMethods
636
- module Object
637
- # Converts this object to a string (calling #to_s), converts
638
- # it to a JSON string, and returns the result. This is a fallback, if no
639
- # special method #to_json was defined for some object.
640
- def to_json(*) to_s.to_json end
641
- end
642
-
643
- module Hash
644
- # Returns a JSON string containing a JSON object, that is unparsed from
645
- # this Hash instance.
646
- # _state_ is a JSON::State object, that can also be used to configure the
647
- # produced JSON string output further.
648
- # _depth_ is used to find out nesting depth, to indent accordingly.
649
- def to_json(state = nil, *)
650
- state = State.from_state(state)
651
- state.check_max_nesting
652
- json_transform(state)
653
- end
654
-
655
- private
656
-
657
- def json_shift(state)
658
- state.object_nl.empty? or return ''
659
- state.indent * state.depth
660
- end
661
-
662
- def json_transform(state)
663
- delim = ','
664
- delim << state.object_nl
665
- result = '{'
666
- result << state.object_nl
667
- depth = state.depth += 1
668
- first = true
669
- indent = !state.object_nl.empty?
670
- each { |key,value|
671
- result << delim unless first
672
- result << state.indent * depth if indent
673
- result << key.to_s.to_json(state)
674
- result << state.space_before
675
- result << ':'
676
- result << state.space
677
- result << value.to_json(state)
678
- first = false
679
- }
680
- depth = state.depth -= 1
681
- result << state.object_nl
682
- result << state.indent * depth if indent if indent
683
- result << '}'
684
- result
685
- end
686
- end
687
-
688
- module Array
689
- # Returns a JSON string containing a JSON array, that is unparsed from
690
- # this Array instance.
691
- # _state_ is a JSON::State object, that can also be used to configure the
692
- # produced JSON string output further.
693
- def to_json(state = nil, *)
694
- state = State.from_state(state)
695
- state.check_max_nesting
696
- json_transform(state)
697
- end
698
-
699
- private
700
-
701
- def json_transform(state)
702
- delim = ','
703
- delim << state.array_nl
704
- result = '['
705
- result << state.array_nl
706
- depth = state.depth += 1
707
- first = true
708
- indent = !state.array_nl.empty?
709
- each { |value|
710
- result << delim unless first
711
- result << state.indent * depth if indent
712
- result << value.to_json(state)
713
- first = false
714
- }
715
- depth = state.depth -= 1
716
- result << state.array_nl
717
- result << state.indent * depth if indent
718
- result << ']'
719
- end
720
- end
721
-
722
- module Integer
723
- # Returns a JSON string representation for this Integer number.
724
- def to_json(*) to_s end
725
- end
726
-
727
- module Float
728
- # Returns a JSON string representation for this Float number.
729
- def to_json(state = nil, *)
730
- state = State.from_state(state)
731
- case
732
- when infinite?
733
- if state.allow_nan?
734
- to_s
735
- else
736
- raise GeneratorError, "#{self} not allowed in JSON"
737
- end
738
- when nan?
739
- if state.allow_nan?
740
- to_s
741
- else
742
- raise GeneratorError, "#{self} not allowed in JSON"
743
- end
744
- else
745
- to_s
746
- end
747
- end
748
- end
749
-
750
- module String
751
- if defined?(::Encoding)
752
- # This string should be encoded with UTF-8 A call to this method
753
- # returns a JSON string encoded with UTF16 big endian characters as
754
- # \u????.
755
- def to_json(state = nil, *args)
756
- state = State.from_state(state)
757
- if encoding == ::Encoding::UTF_8
758
- string = self
759
- else
760
- string = encode(::Encoding::UTF_8)
761
- end
762
- if state.ascii_only?
763
- '"' << JSON.utf8_to_json_ascii(string) << '"'
764
- else
765
- '"' << JSON.utf8_to_json(string) << '"'
766
- end
767
- end
768
- else
769
- # This string should be encoded with UTF-8 A call to this method
770
- # returns a JSON string encoded with UTF16 big endian characters as
771
- # \u????.
772
- def to_json(state = nil, *args)
773
- state = State.from_state(state)
774
- if state.ascii_only?
775
- '"' << JSON.utf8_to_json_ascii(self) << '"'
776
- else
777
- '"' << JSON.utf8_to_json(self) << '"'
778
- end
779
- end
780
- end
781
-
782
- # Module that holds the extinding methods if, the String module is
783
- # included.
784
- module Extend
785
- # Raw Strings are JSON Objects (the raw bytes are stored in an
786
- # array for the key "raw"). The Ruby String can be created by this
787
- # module method.
788
- def json_create(o)
789
- o['raw'].pack('C*')
790
- end
791
- end
792
-
793
- # Extends _modul_ with the String::Extend module.
794
- def self.included(modul)
795
- modul.extend Extend
796
- end
797
-
798
- # This method creates a raw object hash, that can be nested into
799
- # other data structures and will be unparsed as a raw string. This
800
- # method should be used, if you want to convert raw strings to JSON
801
- # instead of UTF-8 strings, e. g. binary data.
802
- def to_json_raw_object
803
- {
804
- JSON.create_id => self.class.name,
805
- 'raw' => self.unpack('C*'),
806
- }
807
- end
808
-
809
- # This method creates a JSON text from the result of
810
- # a call to to_json_raw_object of this String.
811
- def to_json_raw(*args)
812
- to_json_raw_object.to_json(*args)
813
- end
814
- end
815
-
816
- module TrueClass
817
- # Returns a JSON string for true: 'true'.
818
- def to_json(*) 'true' end
819
- end
820
-
821
- module FalseClass
822
- # Returns a JSON string for false: 'false'.
823
- def to_json(*) 'false' end
824
- end
825
-
826
- module NilClass
827
- # Returns a JSON string for nil: 'null'.
828
- def to_json(*) 'null' end
829
- end
830
- end
831
- end
832
- end
833
- end
834
-
835
- module JSON
836
- class << self
837
- # If _object_ is string-like, parse the string and return the parsed result
838
- # as a Ruby data structure. Otherwise generate a JSON text from the Ruby
839
- # data structure object and return it.
840
- #
841
- # The _opts_ argument is passed through to generate/parse respectively. See
842
- # generate and parse for their documentation.
843
- def [](object, opts = {})
844
- if object.respond_to? :to_str
845
- JSON.parse(object.to_str, opts)
846
- else
847
- JSON.generate(object, opts)
848
- end
849
- end
850
-
851
- # Returns the JSON parser class that is used by JSON. This is either
852
- # JSON::Ext::Parser or JSON::Pure::Parser.
853
- attr_reader :parser
854
-
855
- # Set the JSON parser class _parser_ to be used by JSON.
856
- def parser=(parser) # :nodoc:
857
- @parser = parser
858
- remove_const :Parser if JSON.const_defined_in?(self, :Parser)
859
- const_set :Parser, parser
860
- end
861
-
862
- # Return the constant located at _path_. The format of _path_ has to be
863
- # either ::A::B::C or A::B::C. In any case, A has to be located at the top
864
- # level (absolute namespace path?). If there doesn't exist a constant at
865
- # the given path, an ArgumentError is raised.
866
- def deep_const_get(path) # :nodoc:
867
- path.to_s.split(/::/).inject(Object) do |p, c|
868
- case
869
- when c.empty? then p
870
- when JSON.const_defined_in?(p, c) then p.const_get(c)
871
- else
872
- begin
873
- p.const_missing(c)
874
- rescue NameError => e
875
- raise ArgumentError, "can't get const #{path}: #{e}"
876
- end
877
- end
878
- end
879
- end
880
-
881
- # Set the module _generator_ to be used by JSON.
882
- def generator=(generator) # :nodoc:
883
- old, $VERBOSE = $VERBOSE, nil
884
- @generator = generator
885
- generator_methods = generator::GeneratorMethods
886
- for const in generator_methods.constants
887
- klass = deep_const_get(const)
888
- modul = generator_methods.const_get(const)
889
- klass.class_eval do
890
- instance_methods(false).each do |m|
891
- m.to_s == 'to_json' and remove_method m
892
- end
893
- include modul
894
- end
895
- end
896
- self.state = generator::State
897
- const_set :State, self.state
898
- const_set :SAFE_STATE_PROTOTYPE, State.new
899
- const_set :FAST_STATE_PROTOTYPE, State.new(
900
- :indent => '',
901
- :space => '',
902
- :object_nl => "",
903
- :array_nl => "",
904
- :max_nesting => false
905
- )
906
- const_set :PRETTY_STATE_PROTOTYPE, State.new(
907
- :indent => ' ',
908
- :space => ' ',
909
- :object_nl => "\n",
910
- :array_nl => "\n"
911
- )
912
- ensure
913
- $VERBOSE = old
914
- end
915
-
916
- # Returns the JSON generator module that is used by JSON. This is
917
- # either JSON::Ext::Generator or JSON::Pure::Generator.
918
- attr_reader :generator
919
-
920
- # Returns the JSON generator state class that is used by JSON. This is
921
- # either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
922
- attr_accessor :state
923
-
924
- # This is create identifier, which is used to decide if the _json_create_
925
- # hook of a class should be called. It defaults to 'json_class'.
926
- attr_accessor :create_id
927
- end
928
- self.create_id = 'json_class'
929
-
930
- NaN = 0.0/0
931
-
932
- Infinity = 1.0/0
933
-
934
- MinusInfinity = -Infinity
935
-
936
- # The base exception for JSON errors.
937
- class JSONError < StandardError; end
938
-
939
- # This exception is raised if a parser error occurs.
940
- class ParserError < JSONError; end
941
-
942
- # This exception is raised if the nesting of parsed data structures is too
943
- # deep.
944
- class NestingError < ParserError; end
945
-
946
- # :stopdoc:
947
- class CircularDatastructure < NestingError; end
948
- # :startdoc:
949
-
950
- # This exception is raised if a generator or unparser error occurs.
951
- class GeneratorError < JSONError; end
952
- # For backwards compatibility
953
- UnparserError = GeneratorError
954
-
955
- # This exception is raised if the required unicode support is missing on the
956
- # system. Usually this means that the iconv library is not installed.
957
- class MissingUnicodeSupport < JSONError; end
958
-
959
- module_function
960
-
961
- # Parse the JSON document _source_ into a Ruby data structure and return it.
962
- #
963
- # _opts_ can have the following
964
- # keys:
965
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
966
- # structures. Disable depth checking with :max_nesting => false. It defaults
967
- # to 19.
968
- # * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
969
- # defiance of RFC 4627 to be parsed by the Parser. This option defaults
970
- # to false.
971
- # * *symbolize_names*: If set to true, returns symbols for the names
972
- # (keys) in a JSON object. Otherwise strings are returned. Strings are
973
- # the default.
974
- # * *create_additions*: If set to false, the Parser doesn't create
975
- # additions even if a matching class and create_id was found. This option
976
- # defaults to true.
977
- # * *object_class*: Defaults to Hash
978
- # * *array_class*: Defaults to Array
979
- def parse(source, opts = {})
980
- Parser.new(source, opts).parse
981
- end
982
-
983
- # Parse the JSON document _source_ into a Ruby data structure and return it.
984
- # The bang version of the parse method defaults to the more dangerous values
985
- # for the _opts_ hash, so be sure only to parse trusted _source_ documents.
986
- #
987
- # _opts_ can have the following keys:
988
- # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
989
- # structures. Enable depth checking with :max_nesting => anInteger. The parse!
990
- # methods defaults to not doing max depth checking: This can be dangerous
991
- # if someone wants to fill up your stack.
992
- # * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
993
- # defiance of RFC 4627 to be parsed by the Parser. This option defaults
994
- # to true.
995
- # * *create_additions*: If set to false, the Parser doesn't create
996
- # additions even if a matching class and create_id was found. This option
997
- # defaults to true.
998
- def parse!(source, opts = {})
999
- opts = {
1000
- :max_nesting => false,
1001
- :allow_nan => true
1002
- }.update(opts)
1003
- Parser.new(source, opts).parse
1004
- end
1005
-
1006
- # Generate a JSON document from the Ruby data structure _obj_ and return
1007
- # it. _state_ is * a JSON::State object,
1008
- # * or a Hash like object (responding to to_hash),
1009
- # * an object convertible into a hash by a to_h method,
1010
- # that is used as or to configure a State object.
1011
- #
1012
- # It defaults to a state object, that creates the shortest possible JSON text
1013
- # in one line, checks for circular data structures and doesn't allow NaN,
1014
- # Infinity, and -Infinity.
1015
- #
1016
- # A _state_ hash can have the following keys:
1017
- # * *indent*: a string used to indent levels (default: ''),
1018
- # * *space*: a string that is put after, a : or , delimiter (default: ''),
1019
- # * *space_before*: a string that is put before a : pair delimiter (default: ''),
1020
- # * *object_nl*: a string that is put at the end of a JSON object (default: ''),
1021
- # * *array_nl*: a string that is put at the end of a JSON array (default: ''),
1022
- # * *allow_nan*: true if NaN, Infinity, and -Infinity should be
1023
- # generated, otherwise an exception is thrown if these values are
1024
- # encountered. This options defaults to false.
1025
- # * *max_nesting*: The maximum depth of nesting allowed in the data
1026
- # structures from which JSON is to be generated. Disable depth checking
1027
- # with :max_nesting => false, it defaults to 19.
1028
- #
1029
- # See also the fast_generate for the fastest creation method with the least
1030
- # amount of sanity checks, and the pretty_generate method for some
1031
- # defaults for pretty output.
1032
- def generate(obj, opts = nil)
1033
- if State === opts
1034
- state, opts = opts, nil
1035
- else
1036
- state = SAFE_STATE_PROTOTYPE.dup
1037
- end
1038
- if opts
1039
- if opts.respond_to? :to_hash
1040
- opts = opts.to_hash
1041
- elsif opts.respond_to? :to_h
1042
- opts = opts.to_h
1043
- else
1044
- raise TypeError, "can't convert #{opts.class} into Hash"
1045
- end
1046
- state = state.configure(opts)
1047
- end
1048
- state.generate(obj)
1049
- end
1050
-
1051
- # :stopdoc:
1052
- # I want to deprecate these later, so I'll first be silent about them, and
1053
- # later delete them.
1054
- alias unparse generate
1055
- module_function :unparse
1056
- # :startdoc:
1057
-
1058
- # Generate a JSON document from the Ruby data structure _obj_ and return it.
1059
- # This method disables the checks for circles in Ruby objects.
1060
- #
1061
- # *WARNING*: Be careful not to pass any Ruby data structures with circles as
1062
- # _obj_ argument because this will cause JSON to go into an infinite loop.
1063
- def fast_generate(obj, opts = nil)
1064
- if State === opts
1065
- state, opts = opts, nil
1066
- else
1067
- state = FAST_STATE_PROTOTYPE.dup
1068
- end
1069
- if opts
1070
- if opts.respond_to? :to_hash
1071
- opts = opts.to_hash
1072
- elsif opts.respond_to? :to_h
1073
- opts = opts.to_h
1074
- else
1075
- raise TypeError, "can't convert #{opts.class} into Hash"
1076
- end
1077
- state.configure(opts)
1078
- end
1079
- state.generate(obj)
1080
- end
1081
-
1082
- # :stopdoc:
1083
- # I want to deprecate these later, so I'll first be silent about them, and later delete them.
1084
- alias fast_unparse fast_generate
1085
- module_function :fast_unparse
1086
- # :startdoc:
1087
-
1088
- # Generate a JSON document from the Ruby data structure _obj_ and return it.
1089
- # The returned document is a prettier form of the document returned by
1090
- # #unparse.
1091
- #
1092
- # The _opts_ argument can be used to configure the generator. See the
1093
- # generate method for a more detailed explanation.
1094
- def pretty_generate(obj, opts = nil)
1095
- if State === opts
1096
- state, opts = opts, nil
1097
- else
1098
- state = PRETTY_STATE_PROTOTYPE.dup
1099
- end
1100
- if opts
1101
- if opts.respond_to? :to_hash
1102
- opts = opts.to_hash
1103
- elsif opts.respond_to? :to_h
1104
- opts = opts.to_h
1105
- else
1106
- raise TypeError, "can't convert #{opts.class} into Hash"
1107
- end
1108
- state.configure(opts)
1109
- end
1110
- state.generate(obj)
1111
- end
1112
-
1113
- # :stopdoc:
1114
- # I want to deprecate these later, so I'll first be silent about them, and later delete them.
1115
- alias pretty_unparse pretty_generate
1116
- module_function :pretty_unparse
1117
- # :startdoc:
1118
-
1119
- class << self
1120
- # The global default options for the JSON.load method:
1121
- # :max_nesting: false
1122
- # :allow_nan: true
1123
- # :quirks_mode: true
1124
- attr_accessor :load_default_options
1125
- end
1126
- self.load_default_options = {
1127
- :max_nesting => false,
1128
- :allow_nan => true,
1129
- :quirks_mode => true,
1130
- }
1131
-
1132
- # Load a ruby data structure from a JSON _source_ and return it. A source can
1133
- # either be a string-like object, an IO-like object, or an object responding
1134
- # to the read method. If _proc_ was given, it will be called with any nested
1135
- # Ruby object as an argument recursively in depth first order. The default
1136
- # options for the parser can be changed via the load_default_options method.
1137
- #
1138
- # This method is part of the implementation of the load/dump interface of
1139
- # Marshal and YAML.
1140
- def load(source, proc = nil)
1141
- opts = load_default_options
1142
- if source.respond_to? :to_str
1143
- source = source.to_str
1144
- elsif source.respond_to? :to_io
1145
- source = source.to_io.read
1146
- elsif source.respond_to?(:read)
1147
- source = source.read
1148
- end
1149
- if opts[:quirks_mode] && (source.nil? || source.empty?)
1150
- source = 'null'
1151
- end
1152
- result = parse(source, opts)
1153
- recurse_proc(result, &proc) if proc
1154
- result
1155
- end
1156
-
1157
- # Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_
1158
- def recurse_proc(result, &proc)
1159
- case result
1160
- when Array
1161
- result.each { |x| recurse_proc x, &proc }
1162
- proc.call result
1163
- when Hash
1164
- result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
1165
- proc.call result
1166
- else
1167
- proc.call result
1168
- end
1169
- end
1170
-
1171
- alias restore load
1172
- module_function :restore
1173
-
1174
- class << self
1175
- # The global default options for the JSON.dump method:
1176
- # :max_nesting: false
1177
- # :allow_nan: true
1178
- # :quirks_mode: true
1179
- attr_accessor :dump_default_options
1180
- end
1181
- self.dump_default_options = {
1182
- :max_nesting => false,
1183
- :allow_nan => true,
1184
- :quirks_mode => true,
1185
- }
1186
-
1187
- # Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns
1188
- # the result.
1189
- #
1190
- # If anIO (an IO-like object or an object that responds to the write method)
1191
- # was given, the resulting JSON is written to it.
1192
- #
1193
- # If the number of nested arrays or objects exceeds _limit_, an ArgumentError
1194
- # exception is raised. This argument is similar (but not exactly the
1195
- # same!) to the _limit_ argument in Marshal.dump.
1196
- #
1197
- # The default options for the generator can be changed via the
1198
- # dump_default_options method.
1199
- #
1200
- # This method is part of the implementation of the load/dump interface of
1201
- # Marshal and YAML.
1202
- def dump(obj, anIO = nil, limit = nil)
1203
- if anIO and limit.nil?
1204
- anIO = anIO.to_io if anIO.respond_to?(:to_io)
1205
- unless anIO.respond_to?(:write)
1206
- limit = anIO
1207
- anIO = nil
1208
- end
1209
- end
1210
- opts = JSON.dump_default_options
1211
- limit and opts.update(:max_nesting => limit)
1212
- result = generate(obj, opts)
1213
- if anIO
1214
- anIO.write result
1215
- anIO
1216
- else
1217
- result
1218
- end
1219
- rescue JSON::NestingError
1220
- raise ArgumentError, "exceed depth limit"
1221
- end
1222
-
1223
- # Swap consecutive bytes of _string_ in place.
1224
- def self.swap!(string) # :nodoc:
1225
- 0.upto(string.size / 2) do |i|
1226
- break unless string[2 * i + 1]
1227
- string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
1228
- end
1229
- string
1230
- end
1231
-
1232
- # Shortuct for iconv.
1233
- if ::String.method_defined?(:encode)
1234
- # Encodes string using Ruby's _String.encode_
1235
- def self.iconv(to, from, string)
1236
- string.encode(to, from)
1237
- end
1238
- else
1239
- require 'iconv'
1240
- # Encodes string using _iconv_ library
1241
- def self.iconv(to, from, string)
1242
- Iconv.conv(to, from, string)
1243
- end
1244
- end
1245
-
1246
- if ::Object.method(:const_defined?).arity == 1
1247
- def self.const_defined_in?(modul, constant)
1248
- modul.const_defined?(constant)
1249
- end
1250
- else
1251
- def self.const_defined_in?(modul, constant)
1252
- modul.const_defined?(constant, false)
1253
- end
1254
- end
1255
- end
1256
-
1257
- module ::Kernel
1258
- private
1259
-
1260
- # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
1261
- # one line.
1262
- def j(*objs)
1263
- objs.each do |obj|
1264
- puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
1265
- end
1266
- nil
1267
- end
1268
-
1269
- # Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with
1270
- # indentation and over many lines.
1271
- def jj(*objs)
1272
- objs.each do |obj|
1273
- puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
1274
- end
1275
- nil
1276
- end
1277
-
1278
- # If _object_ is string-like, parse the string and return the parsed result as
1279
- # a Ruby data structure. Otherwise, generate a JSON text from the Ruby data
1280
- # structure object and return it.
1281
- #
1282
- # The _opts_ argument is passed through to generate/parse respectively. See
1283
- # generate and parse for their documentation.
1284
- def JSON(object, *args)
1285
- if object.respond_to? :to_str
1286
- JSON.parse(object.to_str, args.first)
1287
- else
1288
- JSON.generate(object, args.first)
1289
- end
1290
- end
1291
- end
1292
-
1293
- # Extends any Class to include _json_creatable?_ method.
1294
- class ::Class
1295
- # Returns true if this class can be used to create an instance
1296
- # from a serialised JSON string. The class has to implement a class
1297
- # method _json_create_ that expects a hash as first parameter. The hash
1298
- # should include the required data.
1299
- def json_creatable?
1300
- respond_to?(:json_create)
1301
- end
1302
- end
1303
-
1304
- JSON.generator = JSON::Pure::Generator
1305
- JSON.parser = JSON::Pure::Parser
1306
- end