summaryrefslogtreecommitdiff
path: root/lib/ffi_yajl/ext.rb
blob: 1441cba9cbdf6bafbde4694a848757915f1e728b (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require 'rubygems'

require 'ffi_yajl/encoder'
require 'ffi_yajl/parser'
require 'ffi'
require 'libyajl2'

module FFI_Yajl
  # FIXME: DRY with ffi_yajl/ffi.rb
  # FIXME: extract map_library_name from FFI and stop requiring it at the top level
  #        so that the C-library can be installed without FFI
  libname = ::FFI.map_library_name("yajl")
  libpath = File.expand_path(File.join(Libyajl2.opt_path, libname))
  libpath.gsub!(/dylib/, 'bundle')
  libpath = ::FFI.map_library_name("yajl") unless File.exist?(libpath)

  #
  # FFS, what exactly was so wrong with DL.dlopen that ruby had to get rid of it???
  #

  def self.try_fiddle_dlopen(libpath)
    require 'fiddle'
    if defined?(Fiddle) && Fiddle.respond_to?(:dlopen)
      ::Fiddle.dlopen(libpath)
      true
    else
      false
    end
  rescue LoadError
    return false
  end

  def self.try_dl_dlopen(libpath)
    require 'dl'
    if defined?(DL) && DL.respond_to?(:dlopen)
      ::DL.dlopen(libpath)
      true
    else
      false
    end
  rescue LoadError
    return false
  end

  def self.try_ffi_dlopen(libpath)
    require 'ffi'
    require 'rbconfig'
    extend ::FFI::Library
    ffi_lib 'dl'
    attach_function 'dlopen', :dlopen, [:string, :int], :void
    if  Config::CONFIG['host_os'] =~ /linux/i
      dlopen libpath, 0x102  # linux: RTLD_GLOBAL | RTLD_NOW
    else
      dlopen libpath, 0
    end
    true
  rescue LoadError
    return false
  end

  unless try_fiddle_dlopen(libpath) || try_dl_dlopen(libpath) || try_ffi_dlopen(libpath)
    raise "cannot find dlopen vi Fiddle, DL or FFI, what am I supposed to do?"
  end

  class Parser
    require 'ffi_yajl/ext/parser'
    include FFI_Yajl::Ext::Parser
  end

  class Encoder
    require 'ffi_yajl/ext/encoder'
    include FFI_Yajl::Ext::Encoder
  end
end