Class: Embulk::PluginRegistry

Inherits:
Object
  • Object
show all
Defined in:
lib/embulk/plugin_registry.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(category, search_prefix) ⇒ PluginRegistry

Returns a new instance of PluginRegistry.



6
7
8
9
10
# File 'lib/embulk/plugin_registry.rb', line 6

def initialize(category, search_prefix)
  @category = category
  @search_prefix = search_prefix
  @map = {}
end

Instance Attribute Details

#category ⇒ Object (readonly)

Returns the value of attribute category.



12
13
14
# File 'lib/embulk/plugin_registry.rb', line 12

def category
  @category
end

Instance Method Details

#lookup(type) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/embulk/plugin_registry.rb', line 19

def lookup(type)
  type = type.to_sym
  if value = @map[type]
    return value
  end
  if search(type)
    if value = @map[type]
      return value
    end
    raise PluginLoadError, "Unknown #{@category} plugin '#{type}'. #{@search_prefix}#{type}.rb is installed but it does not correctly register plugin."
  else
    raise PluginLoadError, "Unknown #{@category} plugin '#{type}'. #{@search_prefix}#{type}.rb is not installed. Run 'embulk gem search -rd embulk-#{@category}' command to find plugins."
  end
end

#register(type, value) ⇒ Object



14
15
16
17
# File 'lib/embulk/plugin_registry.rb', line 14

def register(type, value)
  type = type.to_sym
  @map[type] = value
end

#search(type) ⇒ Object



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
75
76
77
78
79
# File 'lib/embulk/plugin_registry.rb', line 34

def search(type)
  name = "#{@search_prefix}#{type}"
  begin
    require name
    return true
  rescue LoadError => e
    # catch LoadError but don't catch ClassNotFoundException
    # TODO: the best code here is to raise exception only if
    #       `name` file is not in $LOAD_PATH.
    raise e if e.to_s =~ /java.lang.ClassNotFoundException/
  end

  # search from $LOAD_PATH
  load_paths = $LOAD_PATH.map do |lp|
    lpath = File.expand_path(File.join(lp, "#{name}.rb"))
    File.exist?(lpath) ? lpath : nil
  end

  paths = [name] + load_paths.compact.sort  # sort to prefer newer version
  paths.each do |path|
    begin
      require path
      return true
    rescue LoadError => e
      raise e if e.to_s =~ /java.lang.ClassNotFoundException/
    end
  end

  # search gems
  if defined?(::Gem::Specification) && ::Gem::Specification.respond_to?(:find_all)
    specs = Gem::Specification.find_all do |spec|
      spec.contains_requirable_file? name
    end

    # prefer newer version
    specs = specs.sort_by {|spec| spec.version }
    if spec = specs.last
      spec.require_paths.each do |lib|
        require "#{spec.full_gem_path}/#{lib}/#{name}"
      end
      return true
    end
  end

  return false
end