Last active
September 11, 2018 04:19
-
-
Save alissonbrunosa/ffd544b93ab44d97e2d19d176cce8a44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
In this problem you will write a function called populate_template which will take in a template string e.g. " Hello {!first_name} - How are you?" and a hash of fields e.g { "first_name" : "John" } as arguments and will return the template string with the fields inserted in the correct place. | |
The usecase for a function like this would be for instance for answer templates to be used by a support team at a company. | |
So in the previous example you would get: | |
populate_template("Hello {!first_name} - How are you?", {"first_name" => "John"}) | |
and you would get: | |
"Hello John - How are you?" | |
if you called populate_template("Hello {!first_name} - How are you?", {"first_name" => "Mike"}) | |
You would get: | |
"Hello Mike - How are you?" | |
----------------------------------------------------------------------- | |
A few details: | |
Write a function that takes in 2 arguments: | |
- template (String) | |
- fields (hash / dictionary) | |
The populate_template function should support unlimited different fields. You should be able to call: | |
populate_template("Hello {!first_name} {!last_name}", {"first_name" => "Mike", "last_name" => "Smith"}) | |
A template might use the same field several times: | |
populate_template("Hello {!first_name} - I hope everything is going well with you {!first_name}", {"first_name" => "Mike"}) | |
You should print helpful error messages (e.g. missing field in hash) | |
=end | |
class TemplateRenderer | |
def initialize(template, value) | |
@template = template | |
@value = value | |
end | |
def populate_template | |
extract_fields.inject(@template.dup) do |new_template, field| | |
val = @value.fetch clear_field(field) | |
new_template.gsub! field, val | |
end | |
rescue => error | |
puts "Ops! There's no #{error.key} field in #{@value}" | |
end | |
private | |
def extract_fields | |
@template.scan(/{!\w+}/).uniq | |
end | |
def clear_field(field) | |
field.gsub /{!|}/, '' | |
end | |
end | |
def populate_template(template, value) | |
TemplateRenderer.new(template, value).populate_template | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment