Created
November 25, 2014 02:33
-
-
Save matthewlehner/3c88e349ecb95375fbab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
location = Location.first | |
location_json = LocationSerializer.new(location).to_json | |
locations = Locations.first(25) | |
locations_json = ArraySerializer.new(locations).to_json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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