[英]Load a YAML file with variable in Ruby
我正在構建一個聊天機器人並將我的“回復”存儲在下面的 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
但是,當我運行它時,我在@user
first_name
上收到“未定義方法”錯誤。 如果我在控制台中運行相同的代碼,它就可以工作。
如何定義像@user
這樣的變量,然后正確加載 YAML 文件?
我建議使用格式規范而不是 ERB。
這導致 YAML 文件中的語法更簡單
- reply_type: text
text: "Welcome %{user_name}"
和一個簡單的讀取方法
@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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.