lib/ixtlan/babel/serializer.rb in ixtlan-babel-0.1.2 vs lib/ixtlan/babel/serializer.rb in ixtlan-babel-0.2.0
- old
+ new
@@ -1,6 +1,8 @@
require 'ixtlan/babel/hash_filter'
+require 'ixtlan/babel/model_filter'
+require 'ixtlan/babel/filter_config'
module Ixtlan
module Babel
class Serializer
def id
@@ -27,16 +29,16 @@
filter.add_custom_serializers(map)
end
private
- def self.filter
- @filter ||= HashFilter.new
+ def self.config
+ @config ||= FilterConfig.new
end
def filter
- @filter ||= self.class.filter.dup
+ @filter ||= @model_or_models.is_a?( Hash ) ? HashFilter.new : ModelFilter.new
end
protected
# for rails
@@ -48,47 +50,69 @@
# for rails
def self.model_name
model.model_name
end
- def self.default_context_key(default)
- filter.default_context_key(default)
+ def self.default_context_key(single = :single, collection = :collection)
+ config.default_context_key(single, collection)
end
def self.add_context(key, options = {})
- filter[key] = options
+ config[key] = options
end
+ def self.root( root )
+ config.root = root
+ end
+
public
- def use(context_or_options)
- filter.use(context_or_options)
+ def use( context_or_options )
+ @context_or_options = context_or_options
self
end
def to_hash(options = nil)
- filter.use(filter.options.dup.merge!(options)) if options
- if @model_or_models.respond_to?(:collect) && ! @model_or_models.is_a?(Hash)
+ setup_filter( options )
+ if collection?
@model_or_models.collect do |m|
- filter_model(attr(m), m)
+ filter_model( m )
end
else
- filter_model(attr(@model_or_models), @model_or_models)
+ filter_model( @model_or_models )
end
end
def to_json(options = nil)
to_hash(options).to_json
end
- def to_xml(options = {})
- opts = filter.options.dup.merge!(options)
- root = opts.delete :root
- fitler.use(opts)
+ def setup_filter(options)
+ o = if collection?
+ self.class.config.collection_options( @context_or_options )
+ else
+ self.class.config.single_options( @context_or_options )
+ end
+ filter.options = o.merge!( options || {} )
+ filter.options[:root] ||= self.class.config.root
+ end
+ private :setup_filter
+
+ def collection?
+ @is_collection ||= @model_or_models.respond_to?(:collect) && ! @model_or_models.is_a?(Hash)
+ end
+ private :collection?
+
+ def to_xml(options = nil)
+ setup_filter
+
result = to_hash
+
+ root = config.root
+
if root && result.is_a?(Array) && root.respond_to?(:pluralize)
- root = root.to_s.pluralize
+ root = root.pluralize
end
result.to_xml :root => root
end
def to_yaml(options = nil)
@@ -101,14 +125,14 @@
model.attributes if model
end
private
- def filter_model(model, data)
+ def filter_model( model )
if root = filter.options[:root]
- {root.to_s => filter.filter(model, data){ |model| attr(model) } }
+ { root.to_s => filter.filter( model ){ |model| attr(model) } }
else
- filter.filter(model, data){ |model| attr(model) }
+ filter.filter( model ){ |model| attr(model) }
end
end
end
end
end