Skip to content

Instantly share code, notes, and snippets.

@swaathi
Last active December 16, 2017 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swaathi/d96d6fe932df026ad8b501a8bf9c6471 to your computer and use it in GitHub Desktop.
Save swaathi/d96d6fe932df026ad8b501a8bf9c6471 to your computer and use it in GitHub Desktop.
Markdown Template Engine
PWD = File.expand_path(File.dirname(__FILE__))
VARIABLE_REGEX = %r{\<[A-Z\-]*\>}
class MTEngineError
class << self
def not_a_file(filepath)
raise "#{filepath} is not a file or does not exist"
end
end
end
class MTEngine
attr_accessor :filepath, :filename, :filecontent, :variables, :values
def initialize(filename)
self.variables = []
self.values = {}
if filename.include? "/"
self.filepath = filename
else
self.filepath = File.join(PWD, filename)
end
extn = File.extname filepath
self.filename = File.basename filepath, extn
MTEngineError.not_a_file(filepath) unless File.file?(filepath)
read!
fetch_variables!
end
def read!
self.filecontent = File.readlines(self.filepath).join
end
def fetch_variables!
self.variables = filecontent.scan(VARIABLE_REGEX).uniq
end
def store_values!
variables.each do |variable|
puts "#{variable}: "
self.values[variable] = gets.chomp
end
values
end
def replace
dup_content = filecontent.dup
variables.each do |variable|
dup_content.gsub! variable, values[variable]
end
dup_content
end
def replace_and_save!
newfilepath = filepath.sub(filename, "#{filename}_#{Time.now.to_i}")
newfile = File.new(newfilepath, "w")
newfile.puts replace
newfile.close
puts "Saved output to #{newfilepath}!"
end
end
# Load file into irb session
irb -r ./markdown-template-engine.rb
# Load the markdown template
> mt = MTEngine.new("/Users/user/markdown.md")
# Store values of all variables in markdown
> mt.store_values!
# Replace all variables with your values
> mt.replace
# Save new file
> mt.replace_and_save!

Variables are strings in the markdown file that are meant to replaced with values with the markdown-template-engine.

They can only be capital letters enclosed in lesser/greater than symbols. They can not contain numbers or lowercase letters. They can however contain hypens (-).

An example for a variable could be, <NAME> or <FULL-NAME>

Variables CAN NOT be, <name> or <full0name>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment