问题
I'm building a chatbot and storing my 'replies' in a Yaml file below:
# say_hello.yml
- reply_type: text
text: "Welcome <%= @user.first_name %>"
- reply_type: delay
duration: 2
- reply_type: text
text: "We're here to help you learn more about something or another."
- reply_type: delay
duration: 2
In order to run the replies I use this method:
def process
@user = User.find(user_id)
replies = YAML.load(ERB.new(File.read("app/bot/replies/say_hello.yml")).result)
replies.each do |reply|
# code for replies...
end
end
When I run this however I'm getting a 'undefined method' error on first_name
for @user
. If I run the same code in a console it works.
How can I define a variable like @user
and then load the YAML file correctly?
回答1:
I would suggest a different approach without ERB based on format specifications.
# in the YAML
- reply_type: text
text: "Welcome %{user_name}"
# in the method
@user = User.find(user_id)
replies = YAML.load(
File.read("app/bot/replies/say_hello.yml") % { user_name: @user.first_name }
)
回答2:
I've figured out a way using binding
. YAML load line with the below and it works great:
replies = YAML.load(ERB.new(File.read("app/bot/replies/say_hello.yml")).result(binding))
来源:https://stackoverflow.com/questions/55104522/load-a-yaml-file-with-variable-in-ruby