lib/pycall/conversion.rb in pycall-0.1.0.alpha.20170224 vs lib/pycall/conversion.rb in pycall-0.1.0.alpha.20170226
- old
+ new
@@ -1,7 +1,43 @@
module PyCall
module Conversions
+ @python_type_map = []
+
+ class TypePair < Struct.new(:pytype, :rbtype)
+ def to_a
+ [pytype, rbtype]
+ end
+ end
+
+ def self.python_type_mapping(pytype, rbtype)
+ @python_type_map.each_with_index do |type_pair, index|
+ next unless pytype == type_pair.pytype
+ type_pair.rbtype = rbtype
+ return
+ end
+ @python_type_map << TypePair.new(pytype, rbtype)
+ end
+
+ def self.to_ruby(pyobj)
+ unless pyobj.kind_of? PyObject
+ raise
+ end
+ @python_type_map.each do |tp|
+ pytype, rbtype = tp.to_a
+ next unless pyobj.kind_of?(pytype)
+ case
+ when rbtype.kind_of?(Proc)
+ return rbtype.(pyobj)
+ when rbtype.respond_to?(:from_python)
+ return rbtype.from_python(pyobj)
+ else
+ return rbtype.new(pyobj)
+ end
+ end
+ pyobj
+ end
+
def self.from_ruby(obj)
case obj
when PyObject
obj
when PyObjectWrapper
@@ -100,11 +136,11 @@
when LibPython.PyUnicode_Type
py_str_ptr = LibPython.PyUnicode_AsUTF8String(self)
return Conversions.convert_to_string(py_str_ptr).force_encoding(Encoding::UTF_8)
when LibPython.PyList_Type
- return Conversions.convert_to_array(self)
+ return PyCall::List.new(self)
when LibPython.PyTuple_Type
return Conversions.convert_to_tuple(self)
when LibPython.PyDict_Type
@@ -112,9 +148,9 @@
when LibPython.PySet_Type
return PyCall::Set.new(self)
end
- self
+ Conversions.to_ruby(self)
end
end
end