Skip to content

Instantly share code, notes, and snippets.

@eminkel
Last active September 14, 2018 02:51
Show Gist options
  • Save eminkel/aad4278951547d220c33efb3c3597901 to your computer and use it in GitHub Desktop.
Save eminkel/aad4278951547d220c33efb3c3597901 to your computer and use it in GitHub Desktop.
Find all values between curly braces in a string and match and replace based on case statement.
# includes Replacer
#
# replace :text
#
# Lookup.new("I am a string with {help_link}, replace me.").perform
# Returns => "I am a string with https://google.com, replace me."
module Replacer
def replace(text)
Lookup.new(text).perform
end
class Lookup
def initialize(body)
@body = body
end
def perform
find_anchors_and_replace
end
private
attr_accessor :body
def find_anchors_and_replace
body.gsub(/\{.*?\}/, mappings)
end
def mappings
matches = {}
body.scan(/\{.*?\}/) { |x| matches[x] = lookup_case(x) }
return matches
end
def lookup_case(anchor)
case anchor
when "{help_link}"
# Do lookup here
return "https://google.com"
else
""
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment