I have a the following data in tmp.yml. My goal is to load the data to mysql database.
I have the following code to load the data from 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
. You need to access them with whatever accessors they provide.
Try doc[0].position
.
First, three hyphens ---
separate multiple documents in yaml. Then the !ruby/object...
followed will deserialize your file to an object, not hash.
In your original code, you only get the AacflmDirection
object as your doc
variable. Use YAML::load_stream
to load all the objects in your 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. So you can get the value by:
doc[0].attributes["position"]
使用YAML::load_file(SITE_PATH)
读取文件并将其转换为Ruby对象。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.