I am writing a script where a user submits certain parameters from CLI
and based on these parameters an XML document is created and
then submitted to another system for further processing. I am new to
object oriented realm and not sure how to organize code in this context.
I have written following Person class where methods for XML
representation and XML submission are defined in the same class. I am
not sure whether this is a good
design/organization and would like to get some feedback on how can I
improve it. What are the factors or questions I should be considering
here? Any comments will be really helpful.
require 'rubygems'
require 'nokogiri' # for xml
require 'processor-client' # to be implemented
# Person class
class Person
attr_accessor :name, :age, :city
def initialize(name, age, city) @name = name @age = age @city = city
end
# Return/express person object in xml format
def my_xml # Nokogiri already has to_xml method
# create xml
pxml = Nokogiri::XML::Builder.new do |xml|
xml.person { xml.name@name
xml.age @age
xml.city @city
}
end
end
# Send Person object in xml format to the processor-system
# I haven't implemented it yet
def send_xml(xml_file)
conn = ProcessorClient::Connection.new
conn.submit(xml_file)
...
...
end
end
I don't think there's much to be improved. Probably the send_xml method
should get the xml by calling the my_xml method rather than through the
parameter. This makes more sense and is also safer (you don't want
abritrary strings to be submitted).
If you're not only dealing with person data, you should write a generic
class for data processing, which generates specific classes for data
sets (like the Struct class in Ruby).
I don't think there's much to be improved. Probably the send_xml method
should get the xml by calling the my_xml method rather than through the
parameter. This makes more sense and is also safer (you don't want
abritrary strings to be submitted).
I was wondering about xml object validation as well and your suggestion
of calling my_xml/to_xml through send_xml seems like a good approach
here.
If you're not only dealing with person data, you should write a generic
class for data processing, which generates specific classes for data
sets (like the Struct class in Ruby).
I am not sure how Person class or data structure is going to look like
at the moment. But I have looked at Struct and OpenStruct classes and
may use it in future revisions.
By the way, you can and should name the method "to_xml". There's
no ambiguity with the "to_xml" of Nokogiri, because those are different
objects. You may also leave out the "require 'rubygems'" in Ruby 1.9.
Yes, but I need this to be portable for Ruby 1.8.7 as well. Thanks for
the suggestion on using to_xml method name in my class as well. I knew
it won't be a namespace conflict, but I wasn't confident whether to use
it or not..