lib/restpack_serializer/serializable.rb in restpack_serializer-0.2.9 vs lib/restpack_serializer/serializable.rb in restpack_serializer-0.2.10
- old
+ new
@@ -14,43 +14,56 @@
include RestPack::Serializer::Attributes
include RestPack::Serializer::SideLoading
class InvalidInclude < Exception; end
- def as_json(model, options = {})
- @model, @options = model, options
+ def as_json(model, context = {})
+ @model, @context = model, context
data = {}
if self.class.serializable_attributes.present?
self.class.serializable_attributes.each do |key, name|
data[key] = self.send(name) if include_attribute?(name)
end
end
+ add_custom_attributes(data)
add_links(model, data)
data
end
+ def custom_attributes
+ {}
+ end
+
private
+ def add_custom_attributes(data)
+ custom = custom_attributes
+ data.merge!(custom) if custom
+ end
+
def add_links(model, data)
self.class.associations.each do |association|
if association.macro == :belongs_to
data[:links] ||= {}
- data[:links][association.name.to_sym] = model.send(association.foreign_key).to_s
+ foreign_key_value = model.send(association.foreign_key)
+ if foreign_key_value
+ data[:links][association.name.to_sym] = foreign_key_value.to_s
+ end
end
end
data
end
def include_attribute?(name)
self.send("include_#{name}?".to_sym)
end
module ClassMethods
- def as_json(model, options = {})
- new.as_json(model, options)
+ def as_json(model, context = {})
+ new.as_json(model, context)
end
def model_name
self.name.chomp('Serializer')
end