Skip to content

Instantly share code, notes, and snippets.

@jjb
Forked from wam/gist:a86c51eaad03689a14fcd0d58e6cca0c
Last active March 16, 2017 22:19
Show Gist options
  • Save jjb/52518b0d9e9e5176dd800950f737df61 to your computer and use it in GitHub Desktop.
Save jjb/52518b0d9e9e5176dd800950f737df61 to your computer and use it in GitHub Desktop.
converting img tags to ruby image_tag helper

intro

Goal is to convert

<img src="<%= ENV["IMAGE_URL"] %>/icons/app-ui-logo-white.png" id="topbar-logo" alt="Freedom logo">

to

<%= image_tag("/static/images/icons/app-ui-logo-white.png", id: "topbar-logo", alt: "Freedom logo") =>

Thanks to @wam for help with this

notes

  1. each step shows the match string and the replacement string. these were used in SublimeText, YMMV in other engines. the beginning and end / are not needed, they are there just for syntax highlighting.
  2. i have the match strings below set as "ruby" syntax, just so i can get the regex highlighting
  3. these steps don't account for self-closing img tags. those are easy to find and clean up in a final step
  4. img tags that have no attributes won't be picked up by this recipe. it will be easy to change it to do that, but I didin't need that when I was making this so I didin't experiment with making it more flexible.

pass 1

/<img (.*) src="<%= ENV\["IMAGE_URL"\] %>([^"]+)" ([^>]+)>/
<img src="<%= ENV\["IMAGE_URL"\] %>$2" $1 $3>

pass 2

/<img src="<%= ENV\["IMAGE_URL"\] %>([^"]+)" ([^>]+)>/
<%= image_tag("/static/images$1", $2) %>

pass 3

/",\s*(\w+)="([^"]+)"/
", $1: "$2",

May need to run multiple times depending on Regex engine/settings.

pass 4

/,\)/
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment