Class: Avatar::Source::StringSubstitutionSource
- Inherits:
-
Object
- Object
- Avatar::Source::StringSubstitutionSource
- Includes:
- AbstractSource
- Defined in:
- lib/avatar/source/string_substitution_source.rb
Overview
Like a StaticUrlSource, but allows variable replacement within the string. Usage:
source = StringSubstitutionSource.new('#{gender}_icon_#{size}.png')
url = source.avatar_url_for(@person, :gender => :female, :size => :large)
# => 'female_icon_large.png'
Instance Attribute Summary collapse
-
#url ⇒ Object
Returns the value of attribute url.
Instance Method Summary collapse
-
#avatar_url_for(person, options = {}) ⇒ Object
Returns nil if
person
is nil or if variables inurl
remain un-bound after substitutingoptions
; otherwise, returns the result of replacing each variable withinurl
with the value of the corresponding key withinoptions
. -
#initialize(url) ⇒ StringSubstitutionSource
constructor
Create a new source with static url
url
, which can contain any number of variables to be subsituted throughoptions
.
Constructor Details
#initialize(url) ⇒ StringSubstitutionSource
Create a new source with static url url
, which can contain any number of variables to be subsituted through options
. Strings should be of the form ‘…#variable_a…#variable_b…’. note the single quotes. Double quotes will cause the variables to be substituted at Source-creation (when #new is called), which is almost certainly <strong>not</strong> what you want.
21 22 23 24 |
# File 'lib/avatar/source/string_substitution_source.rb', line 21 def initialize(url) raise ArgumentError.new("URL cannot be nil") if url.nil? @url = url.to_s end |
Instance Attribute Details
#url ⇒ Object
Returns the value of attribute url.
13 14 15 |
# File 'lib/avatar/source/string_substitution_source.rb', line 13 def url @url end |
Instance Method Details
#avatar_url_for(person, options = {}) ⇒ Object
Returns nil if person
is nil or if variables in url
remain un-bound after substituting options
; otherwise, returns the result of replacing each variable within url
with the value of the corresponding key within options
.
30 31 32 33 34 |
# File 'lib/avatar/source/string_substitution_source.rb', line 30 def avatar_url_for(person, = {}) return nil if person.nil? result = apply_replacement() result =~ /#\{.*\}/ ? nil : result end |