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
Also, my ruby version is:
ruby 1.8.4 (2005-12-24) [i686-darwin8.7.3]
Adam B. schrieb:
sp = super("/dev/tty.KeySerial1", 9600, 8, 1, 0)
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
Pit C. wrote:
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