Posted about 1 month ago. Visible to the public. Linked content. Auto-destruct in 12 days

Updated: Generating test images on the fly via JavaScript or Ruby

Added Ruby example implementation.

Changes

  • -When you need test images, instead of using services like [lorempixel](https://lorempixel.com/) or [placehold.it](https://placeholder.com/) you may generate test images yourself. You can do this via JavaScript.
  • +When you need test images, instead of using services like [lorempixel](https://lorempixel.com/) or [placehold.it](https://placeholder.com/) you may generate test images yourself.
  • -Here is an ES6 function that generates a simple SVG image and returns it as a `data:` URI. All browsers support SVG, and you can easily adjust it yourself.
  • +Here we build a simple SVG image and wrap it into a `data:` URI. All browsers support SVG, and you can easily adjust it yourself.
  • +Simply set it as an image's `src` attribute.
  • +
  • +
  • +## JavaScript
  • +
  • +Simple solution in modern JavaScript, e.g. for use in the client's browser:
  • +
  • function svgUri(text) {
  • let svg = `
  • <svg width="320" height="240" xmlns="http://www.w3.org/2000/svg">
  • <rect x="0" y="0" width="320" height="240" style="fill: #ddd; stroke: #666; stroke-width: 4;" />
  • <text x="50%" y="50%" font-size="24" text-anchor="middle" alignment-baseline="middle" fill="#666">
  • ${text}
  • </text>
  • </svg>
  • `
  • return 'data:image/svg+xml;charset=utf8,' + window.escape(svg)
  • }
  • -You can simply set this as an image's `src` attribute. See the attached JSFiddle for an example.
  • +See the attached JSFiddle for an example.
  • +
  • +
  • +## Ruby
  • +
  • +If you like to do it on the server, here is some Ruby for you:
  • +
  • + def svg_uri(text)
  • + svg = <<~SVG
  • + <svg width="480" height="270" xmlns="http://www.w3.org/2000/svg">
  • + <rect x="0" y="0" width="480" height="270" style="fill: #ddd; stroke: #666; stroke-width: 4;" />
  • + <text x="50%" y="50%" font-size="24" text-anchor="middle" alignment-baseline="middle" fill="#666">
  • + #{text}
  • + </text>
  • + </svg>
  • + SVG
  • +
  • + "data:image/svg+xml;charset=utf8,#{ERB::Util.url_encode(svg)}"
  • + end

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 1 month ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more