Created
October 5, 2023 16:00
-
-
Save Genkilabs/71b479e1b1300a581a85e047db1cbb43 to your computer and use it in GitHub Desktop.
Revisions
-
Genkilabs created this gist
Oct 5, 2023 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,16 @@ 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