class SmartDump::YamlCreator

Public Class Methods

new(path:, included_models: nil, excluded_models: nil) click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 5
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

Public Instance Methods

dump_models!() click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 12
def dump_models!
  make_data_directory!
  @models_to_be_saved.each { |model| format_and_write_yaml_file!(model) }
end

Private Instance Methods

default_model_list() click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 47
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
fetch_model_instances(model) click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 29
def fetch_model_instances(model)
  model.unscoped.all.order('id ASC')
end
format_and_write_yaml_file!(model) click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 23
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
format_instances(model:, instances:) click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 33
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
generate_file_name(model) click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 69
def generate_file_name(model)
  model.table_name
end
get_relevant_models() click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 55
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
make_data_directory!() click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 19
def make_data_directory!
  FileUtils::mkdir_p(@path)
end
write_yaml_file!(model:, data:) click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 43
def write_yaml_file!(model:, data:)
  File.open(yaml_file_path(model), 'w') { |file| file << data.to_yaml }
end
yaml_file_path(model) click to toggle source
# File lib/smart_dump/yaml_creator.rb, line 65
def yaml_file_path(model)
  File.join(@path, generate_file_name(model) + '.yml')
end