Module: Natto::Binding

Extended by:
FFI::Library
Included in:
MeCab
Defined in:
lib/natto/binding.rb

Overview

Module Binding encapsulates methods and behavior which are made available via FFI bindings to MeCab.

Constant Summary collapse

MECAB_PATH =
'MECAB_PATH'.freeze

Class Method Summary collapse

Class Method Details

.find_libraryString

Returns the absolute pathname to the MeCab library based on the runtime environment.

Returns:

  • (String)

    absolute pathname to the MeCab library

Raises:

  • (LoadError)

    if the library cannot be located


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
# File 'lib/natto/binding.rb', line 22

def self.find_library
  if ENV[MECAB_PATH]
    File.absolute_path(ENV[MECAB_PATH])
  else
    host_os = RbConfig::CONFIG['host_os']

    if host_os =~ /mswin|mingw/i
      require 'win32/registry'
      begin
        base = nil
        Win32::Registry::HKEY_CURRENT_USER.open('Software\MeCab') do |r|
          base = r['mecabrc'].split('etc').first
        end
        lib = File.join(base, 'bin/libmecab.dll')
        File.absolute_path(lib)
      rescue
        raise LoadError, "Please set #{MECAB_PATH} to the full path to libmecab.dll"
      end
    else
      require 'open3'
      if host_os =~ /darwin/i
        ext = 'dylib'
      else
        ext = 'so'
      end

      begin
        base, lib = nil, nil
        cmd = 'mecab-config --libs'
        Open3.popen3(cmd) do |stdin,stdout,stderr|
          toks = stdout.read.split
          base = toks[0][2..-1]
          lib  = toks[1][2..-1]
        end
        File.absolute_path(File.join(base, "lib#{lib}.#{ext}"))
      rescue
        raise LoadError, "Please set #{MECAB_PATH} to the full path to libmecab.#{ext}"
      end
    end
  end
end