Skip to content

Instantly share code, notes, and snippets.

@gmcculloug
Last active May 4, 2020 16:42
Show Gist options
  • Save gmcculloug/b3b232172d5d07885817372f20b56301 to your computer and use it in GitHub Desktop.
Save gmcculloug/b3b232172d5d07885817372f20b56301 to your computer and use it in GitHub Desktop.
Custom Button Export
class ExportArInstances
EXCLUDE_ATTRS = %w(id created_on updated_on created_at updated_at).freeze
def self.export_object(obj, hash)
class_name = obj.class.name.underscore
puts "Exporting #{obj.class.name} [#{obj.try('name')}] with ID: #{obj.id}"
(hash[class_name] ||= []) << item = {'attributes' => export_attributes(obj)}
try(class_name).tap do |has_many_assoc, has_one_assoc|
Array(has_many_assoc).each do |hmn|
puts " has_many: #{hmn}"
obj.send(hmn).each do |o|
export_object(o, (item['has_many'] ||= {}))
end
end
Array(has_one_assoc).each do |hon|
puts " has_one: #{hon}"
export_object(obj.send(hon), (item['has_one'] ||= {}))
end
end
end
def self.export_attributes(obj)
obj.attributes.except(*EXCLUDE_ATTRS)
end
def self.custom_button_set
[['custom_buttons']]
end
def self.custom_button
[nil, ['resource_action']]
end
end
export = CustomButtonSet.find_all_by_class_name("Host").each_with_object({}) do |cbs, export_hash|
ExportArInstances.export_object(cbs, export_hash)
end
puts YAML.dump(export)
class ImportArInstances
DEBUG_MODE = false
def self.import(obj_hash)
new.import(obj_hash)
end
def import(obj_hash)
ActiveRecord::Base.transaction { obj_hash.each { |obj_def| create_object(*obj_def) } }
end
def create_object(class_name, obj_array)
klass = class_name.camelize.constantize
obj_array.collect do |obj|
create_unique_values(obj) if DEBUG_MODE
begin
klass.create!(obj['attributes'].except('guid')).tap do |new_obj|
if obj['has_many'].present?
obj['has_many'].each do |hmo|
new_obj.add_members(create_object(*hmo))
end
end
if obj['has_one'].present?
obj['has_one'].each do |hoo|
new_obj.send("#{hoo.first}=", create_object(*hoo).first)
end
end
try("#{class_name}_post", new_obj)
end
rescue StandardError
puts "Failed to create new instance [#{class_name}] with attributes #{obj['attributes'].inspect}"
raise
end
end
end
def custom_button_set_post(new_obj)
new_obj.set_data[:button_order] = new_obj.custom_buttons.collect(&:id)
new_obj.save!
end
def create_unique_values(obj)
%w(name description).each do |attr_name|
attr_value = obj.dig('attributes', attr_name)
obj.store_path('attributes', attr_name, "#{attr_value} #{Time.zone.now}") if attr_value.present?
end
end
end
ImportArInstances.import(YAML.load_file(ARGV[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment