added singleton

master
Jakub Kuźma 2011-05-31 23:21:15 +02:00
parent e7db196a29
commit 4a6b2d5739
5 changed files with 130 additions and 96 deletions

View File

@ -1,5 +1,15 @@
module Sane class Sane
include Singleton
class << self class << self
extend Forwardable
delegate [:init, :exit, :get_devices, :open, :close, :get_option_descriptor, :get_option, :set_option, :strstatus] => :instance
end
def initialize
init
end
def init def init
version_code = FFI::MemoryPointer.new(:int) version_code = FFI::MemoryPointer.new(:int)
check_status!(API.sane_init(version_code, FFI::Pointer::NULL)) check_status!(API.sane_init(version_code, FFI::Pointer::NULL))
@ -24,7 +34,7 @@ module Sane
def open(device_name) def open(device_name)
device_handle_pointer = FFI::MemoryPointer.new(:pointer) device_handle_pointer = FFI::MemoryPointer.new(:pointer)
check_status!(API.sane_open(device_name.to_s, device_handle_pointer)) check_status!(API.sane_open(device_name, device_handle_pointer))
device_handle_pointer.read_pointer device_handle_pointer.read_pointer
end end
@ -87,8 +97,13 @@ module Sane
end end
end end
def check_status!(status) def strstatus(status)
raise Error.new(API.sane_strstatus(status), status) if status != :good API.sane_strstatus(status)
end end
private
def check_status!(status)
raise Error.new(strstatus(status), status) if status != :good
end end
end end

View File

@ -1,4 +1,4 @@
module Sane class Sane
module API module API
extend FFI::Library extend FFI::Library
@ -12,9 +12,6 @@ module Sane
class Device < FFI::Struct class Device < FFI::Struct
layout :name, :string, :vendor, :string, :model, :string, :type, :string layout :name, :string, :vendor, :string, :model, :string, :type, :string
def to_s; self[:name] end
def inspect; "#<#{self.class.name}:'#{to_s}'>" end
end end
class OptionDescriptor < FFI::Struct class OptionDescriptor < FFI::Struct

View File

@ -1,11 +1,29 @@
module Sane class Sane
class Device class Device
def initialize(handle) def initialize(name)
@handle = handle @name = name
@handle = nil
end
def open
@handle = Sane.open(@name) if closed?
if block_given?
yield self
close
end
end
def closed?
@handle.nil?
end
def opened?
!closed?
end end
def close def close
Sane.close(@handle) Sane.close(@handle) if opened?
@handle = nil
end end
end end
end end

View File

@ -1,4 +1,4 @@
module Sane class Sane
class Error < StandardError class Error < StandardError
attr_reader :status attr_reader :status

View File

@ -1,8 +1,12 @@
require "singleton"
require "forwardable"
require "ffi" require "ffi"
require "sane" require "sane"
require "sane/api" require "sane/api"
require "sane/error" require "sane/error"
require "sane/device"
module Scanner module Scanner