Sha256: 70062a5780cc2902b79868a1f97babc33417ec3150f4a3f5c1d64053c3fe5294

Contents?: true

Size: 1.23 KB

Versions: 3

Compression:

Stored size: 1.23 KB

Contents

require 'rails/generators/active_record'
module Adminpanel
  class DumpGenerator < ActiveRecord::Generators::Base
    desc "Generate a dump for a given resource"
    # source_root File.expand_path("../templates", __FILE__)
    argument :name, type: :string, require: true
    class_option :'inject-into-seeds',
      :type => :boolean,
      :aliases => '-i',
      :default => true,
      :desc => "Skip injection into seeds.rb"

    def create_json_file
      resource = name.demodulize.camelize.singularize
      resource = "Adminpanel::#{resource}".classify.constantize
      file_name = resource.to_s.pluralize.demodulize.downcase + '.json'
      puts "dumping #{resource.display_name.pluralize(I18n.default_locale)} into db/#{file_name}"

      create_file "db/#{file_name}" do
        resource.all.to_a.to_json
      end
      inject_into_seeds(resource, file_name)
    end

  private
    def inject_into_seeds(resource, file_name)
      if options[:'inject-into-seeds']
        append_to_file 'db/seeds.rb' do
          "\nobjects = JSON.parse(open(\"\#{Rails.root}/db/#{file_name}\").read)\n" +
          "objects.each do |element|\n" +
            indent("#{resource}.create element\n", 2) +
          "end\n"
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
adminpanel-2.4.0 lib/generators/adminpanel/dump/dump_generator.rb
adminpanel-2.3.1 lib/generators/adminpanel/dump/dump_generator.rb
adminpanel-2.3.0 lib/generators/adminpanel/dump/dump_generator.rb