Skip to content

Instantly share code, notes, and snippets.

@Genkilabs
Created October 5, 2023 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Genkilabs/71b479e1b1300a581a85e047db1cbb43 to your computer and use it in GitHub Desktop.
Save Genkilabs/71b479e1b1300a581a85e047db1cbb43 to your computer and use it in GitHub Desktop.
Interpolate Sting Using Hash or Rails Model
module CustomUtils
# This should look for hash keys, or ActiveModel::Base attributes within the string
# while also safeguarding from typing errors.
# Interpolation symbols not provided in the hash should be left unchanged.
# This does NOT support "deep interpolation" eg. "my %{%{nested_key}} string"
#@param String with %{key} interpolation fields
#@param Hash with symbolic keys OR Object with 'attributes' method eg. ActiveModel
#@returns String original with any keys replaced if they are in the hash, others ignored
def self.interpolate str, obj
#For the hash, we need to re-key the hash to be sure, and add default to skip missing interpolations
safe_hash = (defined?(obj.attributes) ? obj.attributes : obj.to_h).symbolize_keys
safe_hash.default_proc = proc{|h, k| "%{#{k}}" }
#On the string side, safeguard any place ther is a symbol inside an interpolated field
str.gsub('%{:', '%{') % safe_hash
end
end
@Genkilabs
Copy link
Author

Usage:
CustomUtils.interpolate "status = %{status}", Resource.first
CustomUtils.interpolate "hello %{world_type} world", {world_type: :wonderful}

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