Saturday, October 27, 2012

Ruby get method arguments

So, say you are writing some Ruby code, and want to get an overview of the arguments for a method, dynamically.

Consider this method with arguments a and b:

def foobar a, b
end

Using method(...), we can pass in the special variable __method__ to get the current method.

In turn, we can get the parameters of the method with .parameters, and we can then iterate over the parameters.

Now our code would look something like this:

def foobar a, b
  method(__method__).parameters.each do |arg|
    # ...
  end
end

In order to get the correct parameter name with it's associated value, the final solution would be:

def foobar a, b
  method(__method__).parameters.each do |arg|
    val = eval arg[1].to_s
    puts "#{arg[1]}: #{val}, #{val.class}"
  end
end

Happy coding!

Tuesday, October 9, 2012

Validate XML and DTD

Back to school again, I found that I needed to write some XML and DTD by hand.

The most important aspect of the process is to have a valid XML document as well as a valid DTD. There are perhaps some online tools for this, but none of them are very intuitive.

However, there is a tool named xmllint which does exactly this.

It is included with libxml (package), so there's a great chance you already have it.

Here is an example on how to use it:

editors.dtd

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT editors (editor)>
<!ELEMENT editor  (title, desc?)>
<!ELEMENT title   (#PCDATA)>
<!ELEMENT desc    (#PCDATA)>

editors.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE editors SYSTEM "editors.dtd">
<editors>
  <editor>
    <title>Vim
    <!--Powerful text editor-->
  </editor>
</editors>

And to validate the DTD and XML, execute the following from your command line:
xmllint --valid editors.xml  --dtdvalid editors.dtd

Note: use can use xmllint to validate XML Schemas just use the above command and replace --dtdvalid with with -schema and provide a schema file instead of the DTD file.

Hope that helps!