oddlyzen
3/5/2009 - 5:36 PM

gistfile1.rb

def serialize_to_json(options={})
  namespace = options[:namespace].nil? ? 'ZEP' : options[:namespace]
  if options[:data]
    list = options[:data]
    js = ""
    js << "<script type=\"text/javascript\">"
    js << "\n\tif (typeof #{namespace} !== 'object') { var #{namespace} = {}; }\n"
    js << "\n\tif (typeof #{namespace}.models !== 'object') { #{namespace}.models = {}; }\n"
    list.each do |obj|
      if obj.respond_to? :to_json
        js << "\t#{namespace}.models.#{obj.class.to_s.downcase} = " + obj.to_json + ";\n" unless obj.nil?
      end
    end
    js << "</script>"
  else
    raise ArgumentException, "Key-value pair (options[:data]) expected."
  end
end