Skip to content

Commit

Permalink
use JsBarcode with Stimulus and importmaps
Browse files Browse the repository at this point in the history
  • Loading branch information
yshmarov committed Oct 21, 2023
1 parent 5aaa282 commit d55bbed
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
17 changes: 17 additions & 0 deletions app/javascript/controllers/barcode_controller.js
@@ -0,0 +1,17 @@
import { Controller } from "@hotwired/stimulus"
import JsBarcode from 'jsbarcode';

// Connects to data-controller="barcode"
export default class extends Controller {
connect() {
const options = {
format: "CODE128",
// format: "CODE39",
lineColor: "#0000FF",
displayValue: false,
width: 2,
margin: 0
}
JsBarcode(this.element, this.element.dataset.code, options)
}
}
7 changes: 7 additions & 0 deletions app/models/product.rb
@@ -1,2 +1,9 @@
class Product < ApplicationRecord
# after_create do
# update(barcode: SecureRandom.hex)
# end

before_create do
self.barcode = SecureRandom.hex
end
end
1 change: 1 addition & 0 deletions app/views/products/_product.html.erb
Expand Up @@ -9,4 +9,5 @@
<%= product.barcode %>
</p>

<img data-controller="barcode" data-code="<%= product.barcode %>">
</div>
1 change: 1 addition & 0 deletions config/importmap.rb
Expand Up @@ -5,3 +5,4 @@
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
pin "jsbarcode", to: "https://ga.jspm.io/npm:jsbarcode@3.11.5/bin/JsBarcode.js"

0 comments on commit d55bbed

Please sign in to comment.