Skip to content

Instantly share code, notes, and snippets.

@Genkilabs
Created October 5, 2023 16:00
Show Gist options
  • Select an option

  • Save Genkilabs/71b479e1b1300a581a85e047db1cbb43 to your computer and use it in GitHub Desktop.

Select an option

Save Genkilabs/71b479e1b1300a581a85e047db1cbb43 to your computer and use it in GitHub Desktop.

Revisions

  1. Genkilabs created this gist Oct 5, 2023.
    16 changes: 16 additions & 0 deletions custom_utils.rb
    Original 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