我正在构建一个聊天机器人并将我的“回复”存储在下面的Yaml文件中:
# 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
为了运行回复,我使用这种方法:
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
当我运行这个但是我在first_name
上为@user
得到一个'未定义的方法'错误。如果我在控制台中运行相同的代码,它的工作原理。
如何定义像@user
这样的变量然后正确加载YAML文件?
如果没有基于format specifications的ERB,我会提出一个不同的方法。
# 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 }
)
我已经找到了使用binding
的方法。 YAML加载线与下面的工作很好:
replies = YAML.load(ERB.new(File.read("app/bot/replies/say_hello.yml")).result(binding))