Skip to content

Instantly share code, notes, and snippets.

@matthewlehner
Created November 25, 2014 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewlehner/3c88e349ecb95375fbab to your computer and use it in GitHub Desktop.
Save matthewlehner/3c88e349ecb95375fbab to your computer and use it in GitHub Desktop.
class ArraySerializer
def initialize(objects, *args)
@objects = objects
end
def to_json
serializable_array.to_json.html_safe
end
def serializable_array
@objects.map do |o|
serializer.new(o).serializable_hash
end
end
def serializer
@serializer ||= "#{@objects.first.class}Serializer".constantize
end
end
location = Location.first
location_json = LocationSerializer.new(location).to_json
locations = Locations.first(25)
locations_json = ArraySerializer.new(locations).to_json
class LocationSerializer < BaseSerializer
def initialize(object)
@object = object
end
def to_json
serializable_hash.to_json.html_safe
end
def serializable_hash
Hash.new.tap do |data|
data[:id] = @object.id.to_i
data[:name] = @object.handle
data[:parent_id] = @object.parent_id unless @object.parent_id.blank?
data[:descendant_ids] = @object.descendants.published.map(&:id)
data[:addresses] = @object.addresses.map do |address|
AddressSerializer.new(address).serializable_hash
end
data[:url] = @object.public_path
data[:thumbnail] = "//www.scripps.org/#{@object.image.portrait_thumbnail_url}" if @object.image
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment