-1

I have an instance variable in an active record class called hash_value. It's a serialized hash.

I want to display the hash as XML. Is it right to call hash_value.to_xml? Many nodes are numbers, and XML tags are not allowed to be only number (or start with a number).

I want to override the to_xml method of hash_value. I don't want to override on all hashes, just the hash that's in this record.

class ProductVersion < ActiveRecord::base
   serialize :hash_value, Hash

   def hash_value.to_xml
   end
end

I tried the answer here redefining a single ruby method on a single instance with a lambda but it doesn't seem to be applicable. I suspect because when I load the record, it creates a new hash_value object and thus the singleton adjustment on the original is moot.

Any thoughts would be great. I know I could write a function hash_value_to_xml, but I'd rather avoid doing something like that.

Thanks to the first comment, I came up with a solution. Not a good one, but one that works. I'd love to see if there's a better way, because this one smells a bit.

class MyHash < Hash
    def to_xml
      1/0 #to see if it's run. 
    end
  end
  def hash_value
    MyHash.new().merge(  attributes['hash_value'] );
  end
Community
  • 1
  • 1
baash05
  • 4,394
  • 11
  • 59
  • 97

1 Answers1

1

I would personally go for hash_value_to_xml route. But since you insist, here's an idea that might work (haven't tested that)

class ProductVersion < ActiveRecord::base
   serialize :hash_value, Hash

   alias_method :old_hash_value, :hash_value

   def hash_value
     h = old_hash_value
     h.define_singleton_method(:to_xml) do
      # your custom xml logic here
     end
     h
   end
end

The idea is that you intercept value returned from hash_value and patch it on the fly.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • I didn't do the alias I just used super, but man that was cool, and exactly what I was looking for. I didn't want to go with the underscore version because I don't want my user to know they aren't getting the normal to_xml. Especially since the native to_xml returns invalid xml E – baash05 Jun 27 '13 at 07:09