Skip to content

Instantly share code, notes, and snippets.

@avit
Last active May 9, 2016
Embed
What would you like to do?
Normalizer to add prefix on root-relative paths
Normalizr.configure do |config|
# Match root-relative paths that begin with a leading slash
#
# (/path/to/image.jpg) in CSS url(/...)
# "/path/to/image.jpg" in HTML src="/..."
# '/path/to/image.jpg' in HTML src='/...'
#
# The contents of the parentheses or quotes are captured as matches that can
# be prefixed with a hostname for absolute URLs.
#
ROOT_RELATIVE_PATHS = %r{
(?<= # Look behind before match start to find:
\( | # - an opening parenthesis, or
(['"]) # - an opening quote captured as \1 for closing pair
) #
(?= # Then, match the string that follows
/ # if it starts with a leading slash,
(?:\S+?) # has no whitespace and at least one character long,
(?: # and ends with either:
\1 # - the paired opening quote we captured
| \) # - or a closing parenthesis
) #
) #
}x
add :qualify_root_relative do |t, prefix:|
next unless t.present? && t.is_a?(String)
t.gsub(ROOT_RELATIVE_PATHS, prefix)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment