Skip to content

Instantly share code, notes, and snippets.

@kares
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kares/974fda3b6a4233e6d8f7 to your computer and use it in GitHub Desktop.
Save kares/974fda3b6a4233e6d8f7 to your computer and use it in GitHub Desktop.
re-implementing "native" gem APIs (sample)
# Emulates the SerialPort class that uses a native C extension.
class SerialPort < IO
load "java/jna.jar"
load "java/purejavacomm-0.0.21.jar"
java_import 'purejavacomm.CommPortIdentifier'
def initialize(port)
# do what SerialPort C does on Windows (for compat): 0 -> 'COM1'
port = "COM#{port + 1}" if port.is_a?(Integer) && windows?
port_id = CommPortIdentifier.getPortIdentifier(port.to_s)
@serial_port = port_id.open 'MyApp', 1500 # timeout milliseconds
end
def write(buffer)
@serial_port.getOutputStream.write buffer.to_java_bytes
end
def close; @serial_port.close end
# ... etc.
end if defined? JRUBY_VERSION
require 'serialport.so' unless defined? JRUBY_VERSION
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment