Skip to content

Instantly share code, notes, and snippets.

@wyhaines
Created June 15, 2021 20:45
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 wyhaines/9b939ce08ea6f85de08c2802edb774c5 to your computer and use it in GitHub Desktop.
Save wyhaines/9b939ce08ea6f85de08c2802edb774c5 to your computer and use it in GitHub Desktop.
This is an example of some _really_ simple templating in Crystal that leverages method calls which are dispatched dynamically to get the data to fill out the template.
require "./src/send"
struct Template
getter body : String
def initialize(@body)
end
def transform(data)
@body.gsub(/(###([_\w]+)###)/) do |match|
data.send($2)
end
end
end
class DataThing
include Send
getter name : String
def initialize(@name)
end
def class_name
self.class.name
end
def current_time
Time.local
end
end
Send.activate
t = Template.new("I am a template rendered for ###name### and I get my data from an object of type ###class_name###. Oh, and the time is ###current_time###.")
data = DataThing.new("Kirk")
puts t.transform(data)
> crystal run template.cr
I am a template rendered for Kirk and I get my data from an object of type DataThing. Oh, and the time is 2021-06-15 14:44:34 -06:00.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment