module BadgesToSVG
This module’s main method is {BadgesToSVG#replace}. It’s used to parse a string and replace links to PNG badge images with resolution-independent (SVG) ones. This is used by a command-line tool called badges2svg
.
Constants
- RULES
Rules for PNG to SVG replacements. This array is intentionally ordered, because some rules might match the same pattern, so the greedier ones should go first. A rule is a hash with the following keys:
-
:name
: the rule’s name. This must be unique. -
:pattern
the PNG URL pattern. See {BadgesToSVG#compile_pattern} for a pattern overview. -
:string
the URL replacement. The protocol shouldn’t be specified. If you wish to use theshields.io
start your replacement with a slash (/
). -
:domain
(optional): if you specified a custom domain in the:string
key, set this one totrue
to tellBadgesToSVG
not to prepend the default domain.
-
Attributes
@return [String] default domain
@return [String] default protocol
Public Class Methods
Compile a pattern into a regular expression. Patterns are used as handy shortcuts to extract a part of an URL. A pattern written as +%{foo}+ in a string is compiled into a Regexp
that matches an alphanumeric word into a group called foo. @param pattern [String] @return [Regexp] compiled pattern
# File lib/badges2svg.rb, line 134 def compile_pattern(pattern) # don't use .gsub! here or it’ll modify the variable itself, outside of # the function call pattern = pattern.gsub(/\./, '\\.') Regexp.new ("\\b#{pattern.gsub(/%\{(\w+)\}/, "(?<\\1>.+?)")}\\b") end
Replace PNG image URLs with SVG ones when possible in a given string content. This is meant to be used on a README or similar file. @param content [String] @param opts [Hash] this hash is passed to {BadgesToSVG#root_url} and thus
can be used to override the default protocol and domain.
@return [String] the same content with replaced URLs @see RULES
# File lib/badges2svg.rb, line 149 def replace(content, opts={}) root = root_url(opts) RULES.each do |r| if r[:domain] rule_opts = {:protocol => r[:protocol], :domain => ''} myroot = root_url({}.update(opts).update(rule_opts)) else myroot = root end pat = compile_pattern(r[:pattern]) replacement = myroot + r[:string].gsub(/%\{(\w+)\}/, "\\\\k<\\1>") content.gsub!(pat, replacement) end content end
Create a root URL. If nothing is passed, it uses the default protocol and default domain @param opts [Hash] use this parameter to override default protocol
(+:protocol+) and (+:domain+).
@see BadgesToSVG#protocol
@see BadgesToSVG#domain
# File lib/badges2svg.rb, line 124 def root_url(opts={}) "#{opts[:protocol] || @protocol}://#{opts[:domain] || @domain}" end
@return [String] current gem version
# File lib/badges2svg.rb, line 114 def version '0.1.4' end