Last active
January 2, 2016 23:49
-
-
Save Toady00/8378664 to your computer and use it in GitHub Desktop.
I wrote it, but I'm not sure I like it?
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
# Dynamically creating the correct url for downloading elasticsearch package via version number | |
download_url = "https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.10.deb" # can we say elasticsearch one more time? | |
template = '<%= "https://download.#{@domain}.org/#{@domain}/#{@domain}/#{@domain}-#{@major}.#{@minor}.#{@patch}.deb" %>' | |
vars = {domain: 'elasticsearch', major: 0, minor: 90, patch: 10} | |
url_template = UrlTemplate.new(template, vars) | |
url_template.url == download_url | |
#=> true |
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
require 'erb' | |
class UrlTemplate | |
attr_reader :url, :template | |
def initialize(template, erb_vars = {}) | |
@template = ERB.new(template) | |
self.erb_vars = erb_vars | |
@url = interpolate_url | |
end | |
def erb_vars=(value) | |
@erb_vars = normalize_erb_vars(value) | |
end | |
private | |
def erb_vars | |
@erb_vars | |
end | |
def interpolate_url | |
erb_binding_wrapper do |binding| | |
@template.result(binding) | |
end | |
end | |
def erb_binding_wrapper(&block) | |
set_erb_vars | |
value = yield(binding) | |
unset_erb_vars | |
value | |
end | |
def set_erb_vars | |
erb_vars.each do |erb_var, value| | |
instance_variable_set erb_var, value | |
end | |
end | |
def unset_erb_vars | |
erb_vars.each do |erb_var, value| | |
remove_instance_variable erb_var | |
end | |
end | |
def normalize_erb_vars(erb_vars) | |
Hash[ | |
erb_vars.map { |k, v| ["@#{k}".to_sym, v] } | |
] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment