Ruby/XML/YAML

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
м (1 версия)
 

Текущая версия на 17:57, 13 сентября 2010

Содержание

Convert hash to configuration file

require "yaml"
puts ({ "measurements" => "metric" }.to_yaml)
puts ({ :measurements => :metric }.to_yaml)



Output a hash with yaml

require "yaml"
h = {}
h[:name] = "Robert"
h[:nickname] = "Bob"
h[:age] = 43
h[:email_addresses] = {:home => "bob@example.ru",
                       :work => "robert@example.ru"}
puts h.to_yaml



Reading and Writing Configuration Files

require "yaml"
configuration = { "color" => "blue",
                  "font" => "new romain",
                  "font-size"  => 7 }
open("text.cfg", "w") { |f| YAML.dump(configuration, f) }
open("text.cfg") { |f| puts f.read }
open("text.cfg") { |f| YAML.load(f) }



use YAML::dump to convert your Person object array into YAML data

# YAML::load turns YAML code into working Ruby objects
require "yaml"
class Person
  attr_accessor :name, :age
end
yaml_string = <<END_OF_DATA
---
- !ruby/object:Person
  age: 45
  name: Jimmy
- !ruby/object:Person
  age: 23
  name: Laura Smith
END_OF_DATA
test_data = YAML::load(yaml_string)
puts test_data[0].name
puts test_data[1].name



YAML Demo

require "yaml"
class Person
  attr_accessor :name, :age
end
fred = Person.new
fred.name = "Fred Bloggs"
fred.age = 45
laura = Person.new
laura.name = "Laura Smith"
laura.age = 23
test_data = [ fred, laura ]
puts YAML::dump(test_data)



YAML for Marshaling

require "yaml" 
class Special 
    def initialize(valuable, volatile, precious) 
        @valuable = valuable 
        @volatile = volatile 
        @precious = precious 
    end 
    def to_yaml_properties 
        %w{ @precious @valuable } 
    end 
    def to_s 
        "#@valuable #@volatile #@precious" 
    end 
end 
obj = Special.new("Hello", "there", "World") 
puts "Before: obj = #{obj}" 
data = YAML.dump(obj) 
obj = YAML.load(data) 
puts "After: obj = #{obj}" 
obj = Special.new("Hello", "there", "World") 
puts YAML.dump(obj)