Skip to content

Instantly share code, notes, and snippets.

@robwilliams
Created April 23, 2011 21:49
Show Gist options
  • Save robwilliams/939015 to your computer and use it in GitHub Desktop.
Save robwilliams/939015 to your computer and use it in GitHub Desktop.
using to_xml and to_json hiding certain attributes
# require 'rubygems'
require 'active_model'
class LegacyTable
include ActiveModel::Serialization
include ActiveModel::Serializers::JSON
include ActiveModel::Serializers::Xml
attr_accessor :nice_attribute,
:crappy_old_attribute,
:hide_from_xml,
:hide_from_json
def attributes
{
'nice_attribute' => nice_attribute,
'crappy_old_attribute' => crappy_old_attribute,
'hide_from_xml' => hide_from_xml,
'hide_from_json' => hide_from_json
}
end
def method_that_is_not_in_attributes
'method that is not in attributes/db but we want to include'
end
# the clean way to do this would be to override serializable_hash
# but to_xml ignores it so this is best way i could see how to do it
def default_serialization_options
{
:except => ['crappy_old_attribute'],
:methods => ['method_that_is_not_in_attributes']
}
end
# you can also hide or add certain methods/attributes for xml or json specifically
def as_json(options = {})
options ||= {}
options = default_serialization_options.merge(options)
options[:except] << 'hide_from_json'
super(options)
end
def to_xml(options = {})
options ||= {}
options = default_serialization_options.merge(options)
options[:except] << 'hide_from_xml'
super(options)
end
end
lt = LegacyTable.new
puts "serializable_hash"
puts "==="
puts lt.serializable_hash
puts "as json"
puts "==="
puts lt.as_json
puts "to json"
puts "==="
puts lt.to_json
puts "to xml"
puts "==="
puts lt.to_xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment