How to generate Barcode using Barby Gem in Rails 2.3.8

How to generate Barcode using Barby Gem in Rails 2.3.8

2 Minutes Read

ror41-150x150A barcode is a series of vertical black lines with white spaces in between. This series of lines and spaces can be read by a device that can decode them. This would be a barcode reader. In Ruby on Railsthere is a gem called “barby” which generates the barcode with various format.
Here is an example to create barcode using barby & Rails 2.3.8.
Include the barby gems in your config/environment.rb file

config.gem 'barby-chunky_png'
config.gem 'png''RubyInline'

Install the gems by running the commandrake gems:install. Restart the Rails server.

You might face problem to start the server after the gems installed.Comment out the gems “png” & “RubyInline” in the “config/environment.rb” to get the server started.

Create a folder named “Barcodes” to store the barcode images in your “Public” folder.
Add the below lines of code in your controller


The following method will generate the barcode images and store in the “/public/Barcodes” path. Place this method inside the controller.
The “symbology” is the format in which the barcode will be generated. Default is “Code128B”, If you want to generate in different format you can set the “symbology” according to it.

def generate_barcodes(data) # check to see if we don't already have this barcode image uri = CGI.escape(symbology) + '_' + CGI.escape(data) + '.jpg' fname = RAILS_ROOT + '/public/Barcodes/' + uri #fname = '/var/www/html/arc_cloud/arcdevelopment/' + uri
# if the barcode image doesn't already exist then generate and save it
if ! File.exists?(fname)
str = 'Barby::'+symbology+'.new("'+data+'")'
barcode = eval str
rescue Exception => exc
barcode = # fall back to Code128 type B
end, 'w') do |f|
f.write barcode.to_jpg


Following lines of code will call to generate your dynamic barcode


To show the Barcode images call the following lines of code

<img src="/Barcodes/<%= @job_info.job_number %>.jpg" >
Jayadev Das

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘bout Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!

No Comments

Post A Comment

Exit pop up

Before You Go...!

Subscribe to Andolasoft Blog

Stay up to date with the latest techniques of web & mobile app development service tips and our SaaS and open source product news.
Holler Box