[英]How to load yaml with ruby 2.1
I have a the following data in tmp.yml. 我在tmp.yml中有以下数据。 My goal is to load the data to mysql database.
我的目标是将数据加载到mysql数据库。
I have the following code to load the data from tmp.yml: 我有以下代码从tmp.yml加载数据:
$LOAD_PATH.unshift( File.join( File.dirname(__FILE__), 'lib' ) )
require 'yaml'
require 'AacflmDirection' # Just an empty class
SITE_PATH = '/var/www/test/testme/asian_cinema/tmp.yml'
doc = YAML::load( File.open( SITE_PATH ) )
puts doc[0]['attributes']['position'] # Expect position = 1
And I got this error. 我得到了这个错误。 It seems I cannot access it via hash.
看来我无法通过哈希访问它。
load.rb:8:in `<main>': undefined method `[]' for #<AacflmDirection:0x000000023c9fe0> (NoMethodError)
tmp.yml
--- !ruby/object:AacflmDirection
attributes:
position: "1"
film_id: "1"
created_on: 2012-02-06 09:31:31
page_id: "2671"
director_id: "1"
id: "1"
site_id: "173"
director:
film:
page:
site:
--- !ruby/object:AacflmDirector
assets:
attributes:
slug: paul-cox
name: Paul Cox
bio_markup: ""
created_on: 2012-02-06 09:31:39
page_id: "2671"
id: "51"
bio:
site_id: "173"
directions:
draft:
films:
page:
pathprints:
settings_objects:
site:
You're unserializing objects, not hashes. 您要反序列化对象,而不是散列。
doc[0]
is an instance of AacflmDirection
. doc[0]
是AacflmDirection
的实例。 You need to access them with whatever accessors they provide. 您需要使用它们提供的任何访问器来访问它们。
Try doc[0].position
. 尝试
doc[0].position
。
First, three hyphens ---
separate multiple documents in yaml. 首先,三个连字符
---
在yaml中分隔多个文档。 Then the !ruby/object...
followed will deserialize your file to an object, not hash. 然后后面的
!ruby/object...
会将您的文件反序列化为一个对象,而不是哈希。
In your original code, you only get the AacflmDirection
object as your doc
variable. 在原始代码中,您仅将
AacflmDirection
对象作为doc
变量。 Use YAML::load_stream
to load all the objects in your yaml. 使用
YAML::load_stream
加载yaml中的所有对象。
require 'AacflmDirector'
require 'AacflmDirection'
doc = YAML::load_stream( File.open( SITE_PATH ) )
By that you'll get: 这样,您将获得:
=> [#<AacflmDirection:0x007fa62c1c3a48
@attributes=
{"position"=>"1",
"film_id"=>"1",
"created_on"=>2012-02-06 17:31:31 +0800
"page_id"=>"2671",
"director_id"=>"1",
"id"=>"1",
"site_id"=>"173"},
@director=nil,
@film=nil,
@page=nil,
@site=nil>,
#<AacflmDirector:0x007fa62c1bbe10
@assets=nil,
@attributes=
{"slug"=>"paul-cox",
"name"=>"Paul Cox",
"bio_markup"=>"",
"created_on"=>2012-02-06 17:31:39 +0800,
"page_id"=>"2671",
"id"=>"51",
"bio"=>nil,
"site_id"=>"173"},
@directions=nil,
@draft=nil,
@films=nil,
@page=nil,
@pathprints=nil,
@settings_objects=nil,
@site=nil>]
Then add attr_accessor :attributes
in your AacflmDirection
class defination. 然后在您的
AacflmDirection
类定义中添加attr_accessor :attributes
。 So you can get the value by: 因此,您可以通过以下方式获得价值:
doc[0].attributes["position"]
使用YAML::load_file(SITE_PATH)
读取文件并将其转换为Ruby对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.