Created
February 20, 2015 16:50
-
-
Save chsh/b3ebebd898ffdf32aadc to your computer and use it in GitHub Desktop.
Generate barcode SVG for ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # include BarcodeHelper | |
| # call svg_barcode method in view | |
| # e.g. <p><%= svg_barcode('12345') %></p> | |
| # You shouuld implement Barcode class whith returns barcode encoding from string. | |
| module BarcodeHelper | |
| def svg_barcode(token, options = {}) | |
| xdim = (options[:xdim] || 2).to_i | |
| margin = pick_margin_from(options) | |
| height = (options[:height] || 80).to_i | |
| bc = Barcode.new(token) | |
| content_tag :svg, | |
| width: bc.width * xdim + margin[:left] + margin[:right], | |
| height: height + margin[:top] + margin[:bottom] do | |
| bc.encoding_array.each do |offset, width| | |
| concat content_tag :rect, '', | |
| x: margin[:left] + offset * xdim, y: margin[:top], | |
| width: width * xdim, height: height | |
| end | |
| end | |
| end | |
| def pick_margin_from(options) | |
| margin = options[:margin] || {} | |
| margin[:top] ||= 0 | |
| margin[:bottom] ||= 0 | |
| margin[:left] ||= 0 | |
| margin[:right] ||= 0 | |
| margin[:top] = options[:margin_top] if options[:margin_top] | |
| margin[:bottom] = options[:margin_bottom] if options[:margin_bottom] | |
| margin[:left] = options[:margin_left] if options[:margin_left] | |
| margin[:right] = options[:margin_right] if options[:margin_right] | |
| margin | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment