Sha256: 2b96b4096ffd988e8789a45278c2a61d4a6b09c543e58c1e56adef4d5831d137

Contents?: true

Size: 1.88 KB

Versions: 1

Compression:

Stored size: 1.88 KB

Contents

require 'fileutils'

module SmartDump
  class YamlCreator
    def initialize(path:, included_models: nil, excluded_models: nil)
      @path = path
      @included_models = Array(included_models).map(&:constantize)
      @excluded_models = Array(excluded_models).map(&:constantize)
      @models_to_be_saved = get_relevant_models
    end

    def dump_models!
      make_data_directory!
      @models_to_be_saved.each { |model| format_and_write_yaml_file!(model) }
    end

    private

    def make_data_directory!
      FileUtils::mkdir_p(@path)
    end

    def format_and_write_yaml_file!(model)
      instances = fetch_model_instances(model)
      output = format_instances(model: model, instances: instances)
      write_yaml_file!(model: model, data: output)
    end

    def fetch_model_instances(model)
      model.unscoped.all.order('id ASC')
    end

    def format_instances(model:, instances:)
      output = {}
      instances.each.with_index(1) do |instance, index|
        attrs = instance.attributes
        attrs.delete_if{|k,v| v.nil?}
        output["#{model}_#{index}"] = attrs
      end
      output
    end

    def write_yaml_file!(model:, data:)
      File.open(yaml_file_path(model), 'w') { |file| file << data.to_yaml }
    end

    def default_model_list
      Rails.application.eager_load!
      models = ActiveRecord::Base.descendants
      models.select! { |model| model.table_exists? && model.any? }
      models.delete(ActiveRecord::SchemaMigration)
      models
    end

    def get_relevant_models
      if @included_models.present?
        @included_models & default_model_list
      elsif @excluded_models.present?
        default_model_list - @excluded_models
      else
        default_model_list
      end
    end

    def yaml_file_path(model)
      File.join(@path, generate_file_name(model) + '.yml')
    end

    def generate_file_name(model)
      model.table_name
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
smart_dump-0.1.0 lib/smart_dump/yaml_creator.rb