Module: BetterController::Serializer
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/better_controller/serializer.rb
Overview
Base module for serializing resources
Instance Method Summary collapse
-
#serialize(resource, options = {}) ⇒ Hash
Serialize a resource.
-
#serialize_collection(collection, options = {}) ⇒ Array<Hash>
Serialize a collection of resources.
-
#serialize_resource(resource, options = {}) ⇒ Hash
Serialize a single resource.
Instance Method Details
#serialize(resource, options = {}) ⇒ Hash
Serialize a resource
38 39 40 41 42 43 44 45 46 |
# File 'lib/better_controller/serializer.rb', line 38 def serialize(resource, = {}) return nil if resource.nil? if resource.respond_to?(:each) && !resource.is_a?(Hash) serialize_collection(resource, ) else serialize_resource(resource, ) end end |
#serialize_collection(collection, options = {}) ⇒ Array<Hash>
Serialize a collection of resources
52 53 54 |
# File 'lib/better_controller/serializer.rb', line 52 def serialize_collection(collection, = {}) collection.map { |resource| serialize_resource(resource, ) } end |
#serialize_resource(resource, options = {}) ⇒ Hash
Serialize a single resource
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/better_controller/serializer.rb', line 60 def serialize_resource(resource, = {}) result = {} # Add attributes self.class.attributes.each do |attr| result[attr] = resource.send(attr) if resource.respond_to?(attr) end # Add methods self.class.methods.each do |meth| result[meth] = resource.send(meth) if resource.respond_to?(meth) end # Add associations self.class.associations.each do |name, serializer_class| next unless resource.respond_to?(name) association = resource.send(name) serializer = serializer_class.new result[name] = serializer.serialize(association, ) end result end |