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.



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

def barcodable
  :code
end

#barcode_pathObject



84
85
86
# File 'lib/brocade/has_barcode.rb', line 84

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

#barcode_urlObject



80
81
82
# File 'lib/brocade/has_barcode.rb', line 80

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

#create_barcode(opts = {}) ⇒ Object



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

def create_barcode(opts = {})
  barcode = Barby::Code128B.new send(barcodable)
  path = barcode_path
  FileUtils.mkdir_p File.dirname(path)
  File.open(path, 'wb') do |f|
    # Barby's PNG Outputter defaults to a margin of 10px and height of 100px.
    # NOTE: setting the width makes no difference.
    # http://github.com/toretore/barby/blob/master/lib/barby/outputter/png_outputter.rb
    f.write barcode.to_png(self.class.options.merge(opts))
  end
  FileUtils.chmod (0666&~File.umask), path
end

#destroy_barcodeObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/brocade/has_barcode.rb', line 60

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

#klassObject



88
89
90
# File 'lib/brocade/has_barcode.rb', line 88

def klass
  self.class.to_s.underscore.pluralize
end

#partitioned_idObject

Returns the id in a split path form. E.g. Returns 001/234 for an id of 1234.



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

def partitioned_id
  # 1,000,000 records is enough for now.
  ("%06d" % id).scan(/\d{3}/).join('/')
end

#symbologyObject



39
40
41
# File 'lib/brocade/has_barcode.rb', line 39

def symbology
  :code128
end

#update_barcode(opts = {}) ⇒ Object



56
57
58
# File 'lib/brocade/has_barcode.rb', line 56

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