Load a YAML file with variable in Ruby

巧了我就是萌 提交于 2019-12-11 07:33:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!