Module: Tins::StringNamedPlaceholders
- Defined in:
- lib/tins/string_named_placeholders.rb
Overview
A module that provides methods for working with named placeholders in strings.
This module adds functionality to extract named placeholders from strings and assign values to them, making it easier to work with template-style strings that contain named substitution points.
Instance Method Summary collapse
-
#named_placeholders ⇒ Array<Symbol>
Returns an array of symbols representing the named placeholders found in the string.
-
#named_placeholders_assign(hash, default: nil) ⇒ Hash
Assign values to named placeholders from a hash, using a default value for unspecified placeholders.
-
#named_placeholders_interpolate(hash, default: nil) ⇒ String
Interpolate named placeholders in the string with values from a hash.
Instance Method Details
#named_placeholders ⇒ Array<Symbol>
Returns an array of symbols representing the named placeholders found in the string.
This method scans the string for patterns matching named placeholders in the format %name and extracts the placeholder names, returning them as symbols in an array.
named placeholders found in the string.
26 27 28 |
# File 'lib/tins/string_named_placeholders.rb', line 26 def named_placeholders scan(/%\{([^}]+)\}/).inject([], &:concat).uniq.map(&:to_sym) end |
#named_placeholders_assign(hash, default: nil) ⇒ Hash
Assign values to named placeholders from a hash, using a default value for unspecified placeholders.
This method takes a hash of placeholder values and assigns them to the named placeholders found in the string. If a placeholder is not present in the input hash, the provided default value is used instead. The default can be a static value or a proc that receives the placeholder symbol as an argument.
placeholder.
45 46 47 48 49 50 51 |
# File 'lib/tins/string_named_placeholders.rb', line 45 def named_placeholders_assign(hash, default: nil) hash = hash.transform_keys(&:to_sym) named_placeholders.each_with_object({}) do |placeholder, h| h[placeholder] = hash[placeholder] || (default.is_a?(Proc) ? default.(placeholder) : default) end end |
#named_placeholders_interpolate(hash, default: nil) ⇒ String
Interpolate named placeholders in the string with values from a hash.
This method takes a hash of placeholder values and substitutes the named placeholders found in the string with their corresponding values. Placeholders that are not present in the input hash will be replaced with the provided default value.
65 66 67 68 |
# File 'lib/tins/string_named_placeholders.rb', line 65 def named_placeholders_interpolate(hash, default: nil) values = named_placeholders_assign(hash, default:) self % values end |