diff --git a/README.md b/README.md
index 7c246d8..1011de7 100644
--- a/README.md
+++ b/README.md
@@ -90,8 +90,11 @@ module_size - The Pixel size of each module
(defaults 11)
shape_rendering - SVG Attribute: auto | optimizeSpeed | crispEdges | geometricPrecision
(defaults crispEdges)
-standalone - whether to make this a full SVG file, or only an svg to embed in other svg
+standalone - Whether to make this a full SVG file, or only an svg to embed in other svg
(default true)
+svg_attributes - A optional hash of custom SVG attributes. For example you could add `class` and
+ `id` e.g `{ class: "myklass, id: "myid" }`. Existing attributes will be ignored.
+ (default {})
```
Example
```ruby
diff --git a/lib/rqrcode/export/svg.rb b/lib/rqrcode/export/svg.rb
index a4d2aea..9066536 100644
--- a/lib/rqrcode/export/svg.rb
+++ b/lib/rqrcode/export/svg.rb
@@ -5,6 +5,12 @@
module RQRCode
module Export
module SVG
+ DEFAULT_SVG_ATTRIBUTES = [
+ %(version="1.1"),
+ %(xmlns="http://www.w3.org/2000/svg"),
+ %(xmlns:xlink="http://www.w3.org/1999/xlink"),
+ %(xmlns:ev="http://www.w3.org/2001/xml-events")
+ ]
#
# Render the SVG from the Qrcode.
#
@@ -16,19 +22,30 @@ module SVG
# shape_rendering - Defaults to crispEdges
# standalone - wether to make this a full SVG file, or only svg to embed
# in other svg.
+ # svg_attributes - A optional hash of custom SVG attributes. For example you could add `class`
+ # and `id` e.g `{ class: "myklass, id: "myid" }`. Note that using existing attributes will
+ # mean they are duplicated.
#
def as_svg(options = {})
+ # parse options
offset = options[:offset].to_i || 0
color = options[:color] || "000"
shape_rendering = options[:shape_rendering] || "crispEdges"
module_size = options[:module_size] || 11
standalone = options[:standalone].nil? ? true : options[:standalone]
+ svg_attributes = options[:svg_attributes] || {}
# height and width dependent on offset and QR complexity
dimension = (@qrcode.module_count * module_size) + (2 * offset)
+ svg_tag_attributes = (DEFAULT_SVG_ATTRIBUTES + [
+ %(width="#{dimension}"),
+ %(height="#{dimension}"),
+ %(shape-rendering="#{shape_rendering}")
+ ] + svg_attributes.map { |k, v| %(#{k}="#{v}") }).join(" ")
+
xml_tag = %()
- open_tag = %(})
end
+
+ it "renders id when `svg_attributes[:id]` is provided " do
+ doc = RQRCode::QRCode.new("qrcode").as_svg(svg_attributes: {id: "123"})
+ # For now we do very naive pattern matching. The alternative is to
+ # include a librariry for parsing XML, like nokogiri. That is a big
+ # change for such a small test, though.
+ expect(doc).to match(%r{})
+ end
+
+ it "renders class when `svg_attributes[:class]` is provided " do
+ doc = RQRCode::QRCode.new("qrcode").as_svg(svg_attributes: {class: "foo"})
+ # For now we do very naive pattern matching. The alternative is to
+ # include a librariry for parsing XML, like nokogiri. That is a big
+ # change for such a small test, though.
+ expect(doc).to match(%r{})
+ end
end
end