Sha256: 9ca1140e3eff22e7b3ccb8beb758b26a382d968b01476538f9a259391b99147d

Contents?: true

Size: 1.72 KB

Versions: 21

Compression:

Stored size: 1.72 KB

Contents

module Extface
  class Device < ActiveRecord::Base
    attr_writer :driver_class
    belongs_to :extfaceable, polymorphic: true
    belongs_to :driver, inverse_of: :device
    has_many :jobs, inverse_of: :device
    
    accepts_nested_attributes_for :driver
    
    delegate :print?, :fiscal?, :raw?, :report?, to: :driver, 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?
    end
    
    before_save do
      if @driver_class.present? and @driver_class != driver_class.try(:to_s)
        driver.try(:destroy)
        self.driver = @driver_class.constantize.create if @driver_class.present?
      end
    end
    
    def driver_class
      driver.try(:class)
    end
    
    def driver_name
      driver_class::NAME if driver_class
    end

    def session(description = nil)
      job = jobs.create!(description: description, started_at: Time.now)
      job.thread = Thread.new do
        Thread.current[:extface_job] = job.id
        ActiveRecord::Base.establish_connection unless ActiveRecord::Base.connection.active?
        begin
          raise 'No driver configured' unless driver.present?
          if driver.set_job(job)
            yield driver
            job.complete!
          else
            raise driver.errors.full_messages.join(', ')
          end
        rescue => e
          STDERR.puts e.message
          e.backtrace.each do |line|
            p line
          end
          job.failed! e.message
        ensure
          ActiveRecord::Base.connection.close unless Thread.list.select{ |t| t[:extface_job].present? }.many?
        end
      end
      job
    end

  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
extface-0.7.3 app/models/extface/device.rb
extface-0.7.2 app/models/extface/device.rb
extface-0.7.1 app/models/extface/device.rb
extface-0.7.0 app/models/extface/device.rb
extface-0.6.9 app/models/extface/device.rb
extface-0.6.8 app/models/extface/device.rb
extface-0.6.7 app/models/extface/device.rb
extface-0.6.6 app/models/extface/device.rb
extface-0.6.5 app/models/extface/device.rb
extface-0.6.4 app/models/extface/device.rb
extface-0.6.3 app/models/extface/device.rb
extface-0.6.2 app/models/extface/device.rb
extface-0.6.1 app/models/extface/device.rb
extface-0.6.0 app/models/extface/device.rb
extface-0.5.9 app/models/extface/device.rb
extface-0.5.8 app/models/extface/device.rb
extface-0.5.7 app/models/extface/device.rb
extface-0.5.6 app/models/extface/device.rb
extface-0.5.5 app/models/extface/device.rb
extface-0.5.4b app/models/extface/device.rb