如何在Rails中加载此yml文件?

时间:2019-01-02 19:53:53

标签: ruby-on-rails ruby parsing yaml

我从无法联系到的同事那里收到了这个yml数据文件。我需要加载它才能获取数据,但不确定如何:

---
- !ruby/object:Question
  concise_attributes:
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: id
    value_before_type_cast: 1
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: name
    value_before_type_cast: Trip Summary
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: question
    value_before_type_cast: Please state your general feelings about itinerary, the
      group, and the operations. How did it go overall?
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: created_at
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: updated_at
  new_record: false
  active_record_yaml_version: 2
- !ruby/object:Question
  concise_attributes:
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: id
    value_before_type_cast: 2
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: name
    value_before_type_cast: Itinerary
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: question
    value_before_type_cast: Did you and the clients like the itinerary? If not, why
      not? How could it be improved? Was it accurate? Did you make any adjustments
      to the itinerary? Please describe any special things you did on the trip that
      were not part of the itinerary.
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: created_at
  - !ruby/object:ActiveModel::Attribute::FromDatabase
    name: updated_at
  new_record: false
  active_record_yaml_version: 2

我的第一个猜测是使用yaml_db gem,然后直接使用YAML :: load_file本身,但出现错误:

ArgumentError: undefined class/module Question

即使应用程序中有一个Question模型”

class Question < ActiveRecord::Base
end

1 个答案:

答案 0 :(得分:0)

它似乎已用ActiveModel::AttributeSet::YAMLEncoder编码。您可以使用decode方法来解析yaml文件。 concise_attributes的使用对于YAMLEncoder是特有的。

Rails Source Code

编辑:当文件位于ActiveModel下时,要在控制台中加载文件,请使用ActiveRecord::AttributeSet::YAMLEncoder