Skip to content

Instantly share code, notes, and snippets.

@suhlig
Last active July 20, 2018 18:52
Show Gist options
  • Save suhlig/a7ab8b03cf249b0a1261c6861f303a3a to your computer and use it in GitHub Desktop.
Save suhlig/a7ab8b03cf249b0a1261c6861f303a3a to your computer and use it in GitHub Desktop.
'Blocky' ERB syntax
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