Skip to content

Commit

Permalink
Add ECR.render for rendering without setting up an IO (#6371)
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota authored and Serdar Dogruyol committed Jul 15, 2018
1 parent 249a2ed commit a2f4d61
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
4 changes: 4 additions & 0 deletions spec/std/ecr/ecr_spec.cr
Expand Up @@ -64,4 +64,8 @@ describe "ECR" do
ECR.embed "#{__DIR__}/../data/test_template6.ecr", io
io.to_s.should eq("string with -%")
end

it ".render" do
ECR.render("#{__DIR__}/../data/test_template2.ecr").should eq("123")
end
end
42 changes: 38 additions & 4 deletions src/ecr/macros.cr
Expand Up @@ -38,11 +38,11 @@ module ECR
end
end

# Embeds an ECR file contained in *filename* into the program.
# Embeds an ECR file *filename* into the program and appends the content to
# an IO in the variable *io_name*.
#
# The generated code is the result of translating the contents of
# the ECR file to Crystal, a program that appends to the IO
# with the given *io_name*.
# the ECR file to Crystal, a program that appends to an IO.
#
# ```text
# # greeting.ecr
Expand All @@ -59,7 +59,7 @@ module ECR
# io.to_s # => "Hello World!"
# ```
#
# The `ECR.embed` line basically generates this:
# The `ECR.embed` line basically generates this Crystal code:
#
# ```
# io << "Hello "
Expand All @@ -69,4 +69,38 @@ module ECR
macro embed(filename, io_name)
\{{ run("ecr/process", {{filename}}, {{io_name.id.stringify}}) }}
end

# Embeds an ECR file *filename* into the program and renders it to a string.
#
# The generated code is the result of translating the contents of
# the ECR file to Crystal, a program that appends to an IO and returns a string.
#
# ```text
# # greeting.ecr
# Hello <%= name %>!
# ```
#
# ```
# require "ecr/macros"
#
# name = "World"
#
# rendered = ECR.render "greeting.ecr"
# rendered # => "Hello World!"
# ```
#
# The `ECR.render` basically generates this Crystal code:
#
# ```
# String.build do |io|
# io << "Hello "
# io << name
# io << '!'
# end
# ```
macro render(filename)
::String.build do |%io|
::ECR.embed({{filename}}, %io)
end
end
end

0 comments on commit a2f4d61

Please sign in to comment.