Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- app/cyclid/monkey_patches.rb
Overview
Add a method to String
Instance Method Summary collapse
-
#**(other) ⇒ Object
Provide a “safe” version of the % (interpolation) operator; if a key does not exist in arg, catch the KeyError and insert it as a nil value, and continue.
Instance Method Details
#**(other) ⇒ Object
Provide a “safe” version of the % (interpolation) operator; if a key does not exist in arg, catch the KeyError and insert it as a nil value, and continue.
We’re using the ** operator as it’s one that isn’t already used by String, and it’s abusing % already so hey, why not. FTP
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'app/cyclid/monkey_patches.rb', line 47 def **(other) res = nil arg = other ? other.dup : {} begin res = self % arg rescue KeyError => ex # Extract the key name from the exception message (sigh) match = ex..match(/\Akey{(.*)} not found\Z/) key = match[1] # Inject key with a default value and try again arg[key.to_sym] = nil end while res.nil? # rubocop:disable Lint/Loop return res end |