Module: Dpl::Interpolate

Included in:
Interpolator, Provider
Defined in:
lib/dpl/helper/interpolate.rb

Defined Under Namespace

Classes: Interpolator

Instance Method Summary collapse

Instance Method Details

#interpolate(str, args = [], opts = {}) ⇒ Object

Interpolates variables in the given string.

Variables can be contained in scripts, shell commands, and messages. They have the syntax ‘%name` or `%s` (or any other identifier supported by [Kernel#sprintf](ruby-doc.org/core-2.6.3/Kernel.html#method-i-format)).

This supports two styles of interpolation:

  • Named variables ‘%name` and

  • Positional variables.

Named variable names need to match constants on the provider class, or methods on the provider instance, which will be called in order to evaluate the value to be interpolated.

Positional variables can be used if no corresponding method exists, e.g. if the value that needs to be interpolated is an argument passed to a local method.

For example, using named variables:

```ruby
def upload_file
  interpolate('Uploading file %{file} to %{target}')
end

def file
  './file_name'
end

def target
  'target host'
end
```

Using positional variables:

```ruby
def upload_file(file, target)
  interpolate('Uploading file %s to %s', file, target)
end
```

Implementors are encouraged to use named variables when possible, but are free to choose according to their needs.



52
53
54
55
# File 'lib/dpl/helper/interpolate.rb', line 52

def interpolate(str, args = [], opts = {})
  args = args.shift if args.is_a?(Array) && args.first.is_a?(Hash)
  Interpolator.new(str, self, args || {}, opts).apply
end

#obfuscate(str, opts = {}) ⇒ Object

Obfuscates the given string.

Replaces all but the first N characters with asterisks, and paddes the string to a standard length of 20 characters. N depends on the length of the original string.



70
71
72
73
74
75
76
# File 'lib/dpl/helper/interpolate.rb', line 70

def obfuscate(str, opts = {})
  return str if opts[:secure] || !str.blacklisted?

  keep = (str.length / (4.0 + str.length / 5).round).round
  keep = 1 if keep.zero?
  str[0, keep] + '*' * (20 - keep)
end

#varsObject

Interpolation variables as declared by the provider.

By default this contains string option names, but additional methods can be added using Provider::Dsl#vars.



61
62
63
# File 'lib/dpl/helper/interpolate.rb', line 61

def vars
  self.class.vars
end