Class: Avatar::Source::Wrapper::StringSubstitutionSourceWrapper

Inherits:
AbstractSourceWrapper show all
Defined in:
lib/avatar/source/wrapper/string_substitution_source_wrapper.rb

Overview

Wraps a Source using Rails’ AssetTagHelper#image_path, which can turn path URLs (e.g. ‘/images/my_avatar.png’) into absolute URLs( e.g. ‘’).

Instance Attribute Summary collapse

Attributes inherited from AbstractSourceWrapper

#underlying_source

Instance Method Summary collapse

Methods inherited from AbstractSourceWrapper

#avatar_url_for

Methods included from AbstractSource

#avatar_url_for

Constructor Details

#initialize(source, default_options = {}) ⇒ StringSubstitutionSourceWrapper

Returns a new instance of StringSubstitutionSourceWrapper.



14
15
16
17
# File 'lib/avatar/source/wrapper/string_substitution_source_wrapper.rb', line 14

def initialize(source, default_options = {})
  super(source)
  self.default_options = default_options || {}
end

Instance Attribute Details

#default_optionsObject

Returns the value of attribute default_options.



12
13
14
# File 'lib/avatar/source/wrapper/string_substitution_source_wrapper.rb', line 12

def default_options
  @default_options
end

Instance Method Details

#apply_substitution(string, options) ⇒ Object

For each key in options replaces ‘#key’ in string with the corresponding value in options. string should be of the form ‘…#variable_a…#variable_b…’. Note the single quotes. Double quotes will cause the variables to be substituted before this method is run, which is almost certainly <strong>not</strong> what you want.



40
41
42
43
44
45
46
# File 'lib/avatar/source/wrapper/string_substitution_source_wrapper.rb', line 40

def apply_substitution(string, options)
  returning(string.dup) do |result|
    options.each do |k,v|
      result.gsub!(Regexp.new('#\{' + "#{k}" + '\}'), "#{v}")
    end
  end
end

#substitution_needed?(string) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/avatar/source/wrapper/string_substitution_source_wrapper.rb', line 48

def substitution_needed?(string)
  string =~ /#\{.*\}/
end

#wrap(url, person, options = {}) ⇒ Object

Passes url to AssetTagHelper#image_path. Raises an error if it cannot generate a fully-qualified URI. Try setting ActionController::Base.asset_host to avoid this error.



23
24
25
26
27
# File 'lib/avatar/source/wrapper/string_substitution_source_wrapper.rb', line 23

def wrap(url, person, options = {})
  # url will never be nil b/c of guarantee in AbstractSourceWrapper
  result = apply_substitution(url, self.default_options.merge(options))
  substitution_needed?(result) ? nil : result
end