module Ika

Constants

VERSION

Public Instance Methods

export(options = {}, objects = nil) click to toggle source
# File lib/ika.rb, line 152
def export(options = {}, objects = nil)
  ika_export(options, objects)
end
ika_export(options = {}, objects = nil) click to toggle source
# File lib/ika.rb, line 117
def ika_export(options = {}, objects = nil)
  preset_json_with_raw_data = CarrierWave::Uploader::Base.json_with_raw_data
  CarrierWave::Uploader::Base.json_with_raw_data = true
  objects ||= self
  all_symbol = true
  options[:include] ||= []
  options[:include] = [options[:include]] unless options[:include].is_a?(Array)
  options[:include].each do |opt|
    all_symbol = false unless opt.is_a?(Symbol)
  end

  if all_symbol
    if objects.attributes.keys.include? 'type'
      json = objects.to_json(include: options[:include], methods: :type)
    else
      json = objects.to_json(include: options[:include])
    end
    CarrierWave::Uploader::Base.json_with_raw_data = preset_json_with_raw_data
    return json
  end

  obj_hash = Oj.load objects.to_json
  options[:include].each do |relation|
    if relation.is_a?(::Hash)
      relation.keys.each do |property|
        obj_hash[property.to_s] = Oj.load(objects.try(property).includes(relation[property]).export({include: relation[property]}, objects.try(property)))
      end
    elsif relation.is_a?(Symbol)
      obj_hash[relation.to_s] = Oj.load(objects.try(relation).to_json)
    end
  end
  CarrierWave::Uploader::Base.json_with_raw_data = preset_json_with_raw_data
  Oj.dump(obj_hash)
end