Module: RubyPy

Defined in:
lib/ruby.py.rb

Overview

Ruby wrapper for Python modules (based on the PyCall gem).

Class Method Summary collapse

Class Method Details

.import(pym) ⇒ Object

Import a python.module as a RubyPy::Python::Module using the PyCall gem. Methods called on the Ruby module will be sent to the Python module.

Raises:

  • (ArgumentError)


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
# File 'lib/ruby.py.rb', line 11

def self.import(pym)
  # very simple filter to mitigate the risk of code injection attacks
  raise ArgumentError unless pym =~ /\A[-_.A-Za-z0-9]+\Z/

  # convert a python.module.name to a [RubyPy::]Python::Module::Name
  mod = pym.split('.').map do |segment|
    segment.split('_').map(&:capitalize).join
  end

  # create the [RubyPy::]Python::Module::Name hierarchy
  create_module_hierarchy = \
    mod.size.times.map { |i| "module #{mod[0..i].join('::')};end" }.join(';')
  instance_eval(create_module_hierarchy, __FILE__, __LINE__)

  # import the python module into an anonymous module and delegate to it
  instance_eval("#{<<-"BEGIN"}\n#{<<-"NIGEB"}", __FILE__, __LINE__)
    module #{mod.join('::')}
      unless @pycall
        @pycall = Module.new do
          extend ::PyCall::Import
          pyimport #{pym.inspect}, as: 'import'
        end

        def self.method_missing(method_name, *arguments, &block)
          if respond_to_missing?(method_name)
            @pycall.import.send(method_name, *arguments, &block)
          else
            super
          end
        end
        def self.respond_to_missing?(method_name, include_private = false)
          @pycall.import.respond_to?(method_name, include_private)
        end
      end

      self
    end
  NIGEB
end