Theory of Intelligent Falling JBoss and Microsoft News
Sep 27

An example Ruby patch

Ruby, Tech Add comments

Todd Huss posted his thoughts on dealing with patches to dependencies that you rely on, in response to my Tweaking on the bleeding edge: Ruby vs. Java.

Sam Ruby found an issue in Rubys XmlMarkup builder.

He put up a fix for this which is very clean.

I much prefer this to a diff’d file for patch to run. Isn’t it a lot cleaner to see? A patch is real running code.

Also, since you are able to alias :foo :saved_foo you can even do something and call that old method!

#!/usr/bin/env ruby

#--
# Portions copyright 2004 by Jim Weirich (jim.weirichhouse.org).
# Portions copyright 2005 by Sam Ruby (rubys.intertwingly.net).
# All rights reserved.

# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++

require 'config/environment'
require 'builder'
require 'test/unit'

class Builder::XmlMarkup < Builder::XmlBase
def _escape(text, extra={})
result = text.
gsub(%r{&}, '&').
gsub(%r{<}, '<').
gsub(%r{>}, '>')
extra.each_pair {|key,value| result.gsub!(key, value)}
return result
end

# Insert the attributes (given in the hash).
def _insert_attributes(attrs, order=[])
return if attrs.nil?
q = {'"' => '"'}
order.each do |k|
v = attrs[k]
@target << %{ #{k}="#{_escape(v,q)}"} if v
end
attrs.each do |k, v|
@target << %{ #{k}="#{_escape(v,q)}"} unless order.member?(k)
end
end
end

class TestEscaping < Test::Unit::TestCase

def setup
@xml = Builder::XmlMarkup.new
end

def test_element_gt
@xml.title('2>1')
assert_equal '<title>2>1</title>', @xml.target!
end

def test_element_amp
@xml.title('AT&T')
assert_equal '<title>AT&T</title>', @xml.target!
end

def test_element_amp2
@xml.title('&')
assert_equal '<title>&amp;</title>', @xml.target!
end

def test_attr_less
@xml.a(:title => '2>1')
assert_equal '<a title="2>1"/>', @xml.target!
end

def test_attr_amp
@xml.a(:title => 'AT&T')
assert_equal '<a title="AT&T"/>', @xml.target!
end

def test_attr_quot
@xml.a(:title => '"x"')
assert_equal '<a title=""x""/>', @xml.target!
end

end

3 Responses to “An example Ruby patch”

  1. Todd Huss Says:

    I thought this comment was a good description of how to transparently over-ride behaviour for a group of developers in Ruby. Now I better understand how you can quickly and safely fork a core library:

    http://www.jroller.com/comments/thuss/Blog/forking_a_dependency_with_a#comments

  2. freefly Says:

    i want to ruby program to modifikasi my kernel

  3. freefly Says:

    i have plan to making clone my computer, i want linux program,but i have problem with my VGA card pci,please help me,how to making clone with linux,please send address to program ruby to modifikasi ruby patch.thanks b4.

Leave a Reply

Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

Q: Type in the word 'ajax'