在Ruby中加载带有变量的YAML文件 [英] Load a YAML file with variable in Ruby

查看:52
本文介绍了在Ruby中加载带有变量的YAML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个聊天机器人并将我的回复存储在以下Yaml文件中:

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

但是,当我运行此程序时,对于 @user 名字上出现未定义的方法错误。如果我在控制台中运行相同的代码,它将起作用。

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.

如何定义类似 @user 的变量,然后正确加载YAML文件?

How can I define a variable like @user and then load the YAML file correctly?

推荐答案

我建议使用格式规范而不是ERB。

I suggest using format specifications instead of ERB.

这会导致YAML文件中的语法更简单

This leads to a simpler syntax in the YAML file

- 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 }
)

这篇关于在Ruby中加载带有变量的YAML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆