Sha256: 802bce212e5d64b9e22d51bb31fdde0b2fb57bf8868acbb24d6407a949764776

Contents?: true

Size: 1.24 KB

Versions: 4

Compression:

Stored size: 1.24 KB

Contents

module Extface
  class Device < ActiveRecord::Base
    attr_writer :driver
    belongs_to :extfaceable, polymorphic: true
    belongs_to :driveable, polymorphic: true
    has_many :jobs, inverse_of: :device
    
    accepts_nested_attributes_for :driveable
    
    delegate :print?, :fiscal?, :raw?, :cdr?, to: :driveable, allow_nil: true
    
    validates_uniqueness_of :name, :uuid, scope: [:extfaceable_id, :extfaceable_type]
    
    before_create do
      self.uuid = SecureRandom.hex
      self.name = uuid unless name.present?
      self.driveable = @driver.constantize.create if @driver.present?
    end
    
    def driver
      driveable.try(:class)
    end
    
    def driver_name
      driver::NAME if driver
    end

    def session(description = nil)
      job = jobs.create!(description: description)
      Thread.new do
        begin
          raise 'No driver configured' unless driveable.present?
          driveable.set_job(job)
          yield driveable
          job.complete!
        rescue => e
          STDERR.puts e.message
          e.backtrace.each do |line|
            p line
          end
          job.failed! e.message
        ensure
          ActiveRecord::Base.connection.close
        end
      end
      job
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
extface-0.1.0 app/models/extface/device.rb
extface-0.0.8 app/models/extface/device.rb
extface-0.0.7 app/models/extface/device.rb
extface-0.0.6 app/models/extface/device.rb