Module: Brocade::InstanceMethods

Defined in:
lib/brocade/has_barcode.rb

Overview

Wrap the methods below in a module so we can include them only in the ActiveRecord models which declare ‘has_brocade`.

Instance Method Summary collapse

Instance Method Details

#barcodableObject

Returns the name of the method (as a symbol) to call to get the data to be barcoded.

Override this in your model as appropriate.



36
37
38
# File 'lib/brocade/has_barcode.rb', line 36

def barcodable
  :code
end

#barcode(opts = {}) ⇒ Object

Returns a Code128 barcode instance.

opts: :subset - specify the Code128 subset to use (‘A’, ‘B’, or ‘C’).



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/brocade/has_barcode.rb', line 44

def barcode(opts = {})
  data = format_for_subset_c_if_applicable send(barcodable)
  if (subset = opts[:subset])
    case subset
    when 'A'; Barby::Code128A.new data
    when 'B'; Barby::Code128B.new data
    when 'C'; Barby::Code128C.new data
    end
  else
    most_efficient_barcode_for data
  end
end

#barcode_pathObject



99
100
101
# File 'lib/brocade/has_barcode.rb', line 99

def barcode_path
  "#{::Rails.root}/public/system/barcodes/#{klass}/#{partitioned_id}/#{symbology}.png"
end

#barcode_urlObject



95
96
97
# File 'lib/brocade/has_barcode.rb', line 95

def barcode_url
  "/system/barcodes/#{klass}/#{partitioned_id}/#{symbology}.png"
end

#create_barcode(opts = {}) ⇒ Object

Writes a barcode PNG image.

opts: :subset - specify the Code128 subset to use (‘A’, ‘B’, or ‘C’). remaining options passed through to PNGOutputter.



62
63
64
65
66
67
68
69
# File 'lib/brocade/has_barcode.rb', line 62

def create_barcode(opts = {})
  path = barcode_path
  FileUtils.mkdir_p File.dirname(path)
  File.open(path, 'wb') do |f|
    f.write barcode(opts).to_png(self.class.options.merge(opts))
  end
  FileUtils.chmod(0666 &~ File.umask, path)
end

#destroy_barcodeObject



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/brocade/has_barcode.rb', line 75

def destroy_barcode
  path = barcode_path
  begin
    FileUtils.rm path if File.exist? path
  rescue Errno::ENOENT => e
    # Ignore file-not-found; let everything else pass.
  end
  begin
    while true
      path = File.dirname path
      FileUtils.rmdir path
      break if File.exists?(path)  # Ruby 1.9.2 does not raise if the removal failed.
    end
  rescue Errno::EEXIST, Errno::ENOTEMPTY, Errno::ENOENT, Errno::EINVAL, Errno::ENOTDIR, Errno::EACCES
    # Stop trying to remove parent directories
  rescue SystemCallError => e
    # Ignore it
  end
end

#update_barcode(opts = {}) ⇒ Object



71
72
73
# File 'lib/brocade/has_barcode.rb', line 71

def update_barcode(opts = {})
  create_barcode(opts) if changed.include? barcodable
end