Creating ruby-serialport singleton object breaks

A

Adam Block

I'm trying to create a singleton serial port class with the following
code:

require 'serialport' # version 0.6
require 'singleton'

class SerialConnection < SerialPort
include Singleton

def initialize
sp = super("/dev/tty.KeySerial1", 9600, 8, 1, 0)
end
end

But when I try to create the instance it breaks:

irb(main):009:0> sp = SerialConnection.instance
ArgumentError: wrong number of arguments (0 for 1)
from (irb):8:in `new'
from (irb):8:in `new'
from /usr/local/lib/ruby/1.8/singleton.rb:95:in `instance'
from (irb):9

But this works fine:

irb(main):010:0> sp = SerialPort.new("/dev/tty.KeySerial1", 9600, 8, 1,
0)
=> #<SerialPort:0x3251fc>

Any ideas? This used to work, but now it doesn't, and I can't for the
life of me figure out what changed.

Thanks!

/afb
 
P

Pit Capitain

Adam said:
I'm trying to create a singleton serial port class with the following
code:

require 'serialport' # version 0.6
require 'singleton'

class SerialConnection < SerialPort
include Singleton

def initialize
sp = super("/dev/tty.KeySerial1", 9600, 8, 1, 0)
end
end

But when I try to create the instance it breaks:

irb(main):009:0> sp = SerialConnection.instance
ArgumentError: wrong number of arguments (0 for 1)
from (irb):8:in `new'
from (irb):8:in `new'
from /usr/local/lib/ruby/1.8/singleton.rb:95:in `instance'
from (irb):9

Adam, the problem is that SerialPort.new requires at least one argument,
but Singleton.instance calls new without any arguments. You supply the
missing arguments in SerialConnection#initialize, but this is too late,
because SerialPort.new is called before SerialConnection#initialize.
Change your code to

class SerialConnection < SerialPort
def self.new
super("/dev/tty.KeySerial1", 9600, 8, 1, 0)
end

include Singleton
end

and it should work. Note: in order to avoid a warning about redefining
SerialConnection.new, you have to include Singleton *after* defining the
method.

Regards,
Pit
 
A

Adam Block

Pit said:
class SerialConnection < SerialPort
def self.new
super("/dev/tty.KeySerial1", 9600, 8, 1, 0)
end

include Singleton
end

Pit: Thanks so much. It worked perfectly.

/afb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top