Skip to content

Commit

Permalink
Libvirt::Spec::Network
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchellh committed Dec 13, 2010
1 parent 942d213 commit 4d35604
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,7 @@

- `FFI::Libvirt::MissingLibError` is raised if libvirt C library
is not available.
- `Libvirt::Spec::Network` added to parse network interfaces.

## 0.2.0 (December 7, 2010)

Expand Down
8 changes: 8 additions & 0 deletions lib/libvirt/network.rb
Expand Up @@ -24,6 +24,14 @@ def xml
FFI::Libvirt.virNetworkGetXMLDesc(self, 0)
end

# Returns the {Libvirt::Spec::Network} object representing this
# network.
#
# @return [Libvirt::Spec::Network]
def spec
Spec::Network.new(xml)
end

# Returns the UUID of the network as a string.
#
# @return [String]
Expand Down
1 change: 1 addition & 0 deletions lib/libvirt/spec.rb
Expand Up @@ -8,6 +8,7 @@ module Libvirt
module Spec
autoload :Device, 'libvirt/spec/device'
autoload :Domain, 'libvirt/spec/domain'
autoload :Network, 'libvirt/spec/network'
autoload :Util, 'libvirt/spec/util'
end
end
42 changes: 42 additions & 0 deletions lib/libvirt/spec/network.rb
@@ -0,0 +1,42 @@
module Libvirt
module Spec
# A specification of a network interface. This translates directly
# down to XML which can be used to define network interfaces.
class Network
include Util

attr_accessor :name
attr_accessor :uuid

# Initializes a network specification. If a valid XML string is
# given, it will attempt to be parsed into the structure.
def initialize(xml=nil)
load!(xml) if xml
end

# Attempts to load the attributes from an XML specification.
#
# @param [String] xml XML spec to attempt to parse into the structure.
def load!(xml)
root = Nokogiri::XML(xml).root
try(root.xpath("//network")) do |network|
try(network.xpath("name")) { |result| self.name = result.text }
try(network.xpath("uuid")) { |result| self.uuid = result.text }
end
end

# Returns the XML for this specification.
#
# @return [String]
def to_xml
Nokogiri::XML::Builder.new do |xml|
xml.network do
xml.name name if name
xml.uuid uuid if uuid
end
end.to_xml
end
end
end
end

19 changes: 19 additions & 0 deletions test/libvirt/spec/network_test.rb
@@ -0,0 +1,19 @@
require 'test_helper'

Protest.describe("Network spec") do
setup do
@klass = Libvirt::Spec::Network
end

context "initialization with XML parsing" do
should "parse the name" do
@instance = @klass.new("<network><name>foo</name></network>")
assert_equal "foo", @instance.name
end

should "parse the UUID" do
@instance = @klass.new("<network><uuid>foo</uuid></network>")
assert_equal "foo", @instance.uuid
end
end
end

0 comments on commit 4d35604

Please sign in to comment.