Module: FFI_Yajl::FFI::Encoder

Included in:
Encoder
Defined in:
lib/ffi_yajl/ffi/encoder.rb

Instance Method Summary collapse

Instance Method Details

#do_yajl_encode(obj, yajl_gen_opts, opts) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ffi_yajl/ffi/encoder.rb', line 28

def do_yajl_encode(obj, yajl_gen_opts, opts)
  yajl_gen = FFI_Yajl.yajl_gen_alloc(nil);

  # configure the yajl encoder
  if yajl_gen_opts[:yajl_gen_beautify]
    FFI_Yajl.yajl_gen_config(yajl_gen, :yajl_gen_beautify, :int, 1)
  end
  if yajl_gen_opts[:yajl_gen_validate_utf8]
    FFI_Yajl.yajl_gen_config(yajl_gen, :yajl_gen_validate_utf8, :int, 1)
  end
  indent = yajl_gen_opts[:yajl_gen_indent_string] || " "
  FFI_Yajl.yajl_gen_config(yajl_gen, :yajl_gen_indent_string, :string, indent)

  # setup our own state
  state = {
    :json_opts => opts,
    :processing_key => false,
  }

  # do the encoding
  obj.ffi_yajl(yajl_gen, state)

  # get back our encoded JSON
  string_ptr = ::FFI::MemoryPointer.new(:string)
  length_ptr = ::FFI::MemoryPointer.new(:int)
  if ( status = FFI_Yajl.yajl_gen_get_buf(yajl_gen, string_ptr, length_ptr) ) != 0
    FFI_Yajl::Encoder.raise_error_for_status(status)
  end
  length = length_ptr.read_int
  string = string_ptr.get_pointer(0).read_string

  FFI_Yajl.yajl_gen_free(yajl_gen)

  return string
end