Last active
July 20, 2018 18:52
-
-
Save suhlig/a7ab8b03cf249b0a1261c6861f303a3a to your computer and use it in GitHub Desktop.
'Blocky' ERB syntax
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 UserTemplate | |
def initialize(user) | |
@user = user | |
end | |
def to_s | |
# In the ERB template, we can refer to all instance variables, etc. due to | |
# the binding being passed. | |
# | |
# Note how 'blocky' this looks! | |
ERB.new(<<~'EOB').result(binding) | |
To: <%= @user.name %> | |
Dear <%= @user.firstname %>, this is for you. | |
EOB | |
end | |
end | |
User = Struct.new(:lastname, :firstname, keyword_init: true) do | |
def name | |
[self.firstname, self.lastname].join(' ') | |
end | |
end | |
marge = User.new(firstname: 'Marge', lastname: 'Simpson') | |
puts UserTemplate.new(marge) | |
# To: Marge Simpson | |
# | |
# Dear Marge, this is for you. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment