Skip to content

Instantly share code, notes, and snippets.

@noteflakes
Created June 13, 2024 09:28
Show Gist options
  • Save noteflakes/3653ec742d76fe5b6e3557315fe8f503 to your computer and use it in GitHub Desktop.
Save noteflakes/3653ec742d76fe5b6e3557315fe8f503 to your computer and use it in GitHub Desktop.
DB transform algorithm
require 'pp'
SPEC = {
identity_idx: 0,
columns: [
:id,
:title,
{
name: :author,
identity_idx: 0,
columns: [:id, :name]
}
]
}
def get_next_column_value
@counter ||= 0
@counter += 1
end
def get_column_value(idx)
get_next_column_value
end
def process(row_hash, spec)
spec[:columns].each do |c|
case c
when Hash
relation_hash = row_hash[c[:name]] = {}
process(relation_hash, c)
else
row_hash[c] = get_next_column_value
end
end
end
def prepare_spec(spec)
if spec[:identity_idx]
spec[:id_map] = {}
end
spec[:columns].each do |c|
prepare_spec(c) if c.is_a?(Hash)
end
end
def process(spec)
id = get_column_value(spec[:identity_idx])
if (row = spec[:id_map][id])
return row
end
row = {}
populate_row(row, spec)
row
end
def populate_row(row, spec)
spec[:columns].each_with_index do |c, i|
case c
when Hash
row[c[:name]] = process(c)
else
value = row[c] = get_next_column_value
if i == spec[:identity_idx]
spec[:id_map][value] = row
end
end
end
end
prepare_spec(SPEC)
puts "row:"
p process(SPEC)
puts
puts "SPEC:"
pp SPEC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment