Reputation: 2304
I am building a Rails 5.2 app. In this app I let my users save email templates that are then used to send emails to customers. In these templates the users can add placeholder variables, for example %{sender.firstname}.
I need these values to be replaced with actual first name of the sender in this case.
Ruby got a feature that can take care of this (almost).
body = "Hello %{firstname}"
body % { :firstname => "James" }
The above code outputs:
Hello James
The problem is I want to use the prefix sender, like below but then I get an error. Seems like I have to use a single word symbol?
body = "Hello %{sender.firstname}"
body % { "sender.firstname" => "James" }
The error is:
Traceback (most recent call last):
2: from (irb):44
1: from (irb):44:in `%'
KeyError (key{sender.firstname} not found)
How can I use the above method to look through a objects body, replace the variables and output the correct values?
Upvotes: 0
Views: 225
Reputation: 431
Calling #to_sym
on "sender.firstname"
will fix it.
body % { "sender.firstname".to_sym => "James" }
# => "Hello James"
Upvotes: 2