Thursday, 13 September 2012

Generating barcode in ruby on rails

Hi,

In ruby we can generate bar code easily with nice wrapper using barby.


BARBY - The Ruby barcode generator. To know more about barby check the http://toretore.eu/barby/


Here are the simple ruby program to generate barcode in ruby file.

require 'barby'
require 'barby/barcode/code_128'
require 'barby/outputter/png_outputter'

barcode = Barby::Code128B.new('The noise of mankind has become too much')
File.open('code128b.png', 'w'){|f|
  f.write barcode.to_png(:height => 20, :margin => 5)
}



Below is the stepwise instructions to implement barcode in rails application.


Add the below gems to your gem file.


gem 'barby'
gem "has_barcode"


Add the below code to your model to which you would like to generate barcode

class Product < ActiveRecord::Base
  include HasBarcode

  has_barcode :barcode,
    :outputter => :svg,
    :type => :code_39,
    :value => Proc.new { |p| "#{p.id}" }

end



Display the barcode in your view as below

<%= @product.barcode_data.html_safe  %>


By using above simple steps you can generate barcode in rails application.

Thank You,
Uma Mahesh.

1 comment:

  1. This is perfect for my app, thank you!

    Is there a way to configure the height and width of the resulting image?

    ReplyDelete