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 = {}) ⇒ Object



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
# File 'lib/ffi_yajl/ffi/encoder.rb', line 7

def do_yajl_encode(obj, yajl_gen_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