Created
October 5, 2023 16:00
-
-
Save Genkilabs/71b479e1b1300a581a85e047db1cbb43 to your computer and use it in GitHub Desktop.
Interpolate Sting Using Hash or Rails Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
CustomUtils.interpolate "status = %{status}", Resource.first
CustomUtils.interpolate "hello %{world_type} world", {world_type: :wonderful}