Created
June 15, 2021 20:45
-
-
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.
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 "./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) |
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
> 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