./lib/json-exporter/base.rb in json-exporter-0.4.3 vs ./lib/json-exporter/base.rb in json-exporter-0.4.4
- old
+ new
@@ -3,10 +3,11 @@
FILTERS ||= {before:{}, after:{}}
INFLECTOR ||= Dry::Inflector.new
class << self
def define name = nil, &block
+ # if name is given, prepend name, if not, use class name as exporter name
name = name ? "#{INFLECTOR.classify(name)}#{to_s}" : to_s
EXPORTERS[name] = block
end
@@ -20,10 +21,12 @@
def after &block
__define_filter :after, &block
end
+ private
+
def __define_filter name, &block
define_method name do
super() if self.class != JsonExporter
instance_exec &block
end
@@ -35,12 +38,12 @@
attr_accessor :json, :model, :opts
alias :response :json
def initialize model, opts = {}
- if model.is_a?(String) || model.is_a?(Symbol)
- raise ArgumentError, 'model argument is not model instance (it is %s)' % model.class
+ if [String, Symbol].include?(model.class)
+ raise ArgumentError, 'model argument is not model instance (it is a %s)' % model.class
end
opts[:export_depth] ||= 2 # 2 is default depth. if we encounter nested recursive exports, will go only to depth 2
opts[:current_depth] ||= 0
opts[:current_depth] += 1
@@ -57,10 +60,14 @@
after
@json
end
+ def merge data
+ data.each {|k,v| json[k] = v }
+ end
+
def before; end
def after; end
private
@@ -71,12 +78,12 @@
return if @opts[:current_depth] > @opts[:export_depth]
if name.is_a?(Symbol)
name, cmodel = name, @model.send(name)
- if cmodel.respond_to?(:all) && cmodel.respond_to?(:first)
- cmodel = cmodel.all.map { |el| JsonExporter.export(el, @opts.dup) }
+ if cmodel.class.to_s.include?('Array')
+ cmodel = cmodel.map { |el| self.class.export(el, __opts) }
end
else
underscored = INFLECTOR.underscore(name.class.to_s).to_sym
name, cmodel = underscored, name
end
@@ -84,12 +91,11 @@
@json[name] = if [Array].include?(cmodel.class)
cmodel
elsif cmodel.nil?
nil
else
- new_opts = local_opts.merge(export_depth: @opts[:export_depth], current_depth: @opts[:current_depth])
- self.class.new(cmodel, new_opts).render
+ self.class.new(cmodel, __opts(local_opts)).render
end
end
# add property to exporter
def property name, data = :_undefined, &block
@@ -112,9 +118,16 @@
self.class.ancestors.map(&:to_s).each do |klass|
block = EXPORTERS[[base, klass].join] || EXPORTERS[klass]
return block if block
end
- raise(%[Exporter for class "#{base}" not found.])
+ raise %[Exporter for class "#{base}" not found.]
+ end
+
+ def __opts start = {}
+ start.merge(
+ export_depth: @opts[:export_depth],
+ current_depth: @opts[:current_depth]
+ )
end
end