-
-
Save noteflakes/3653ec742d76fe5b6e3557315fe8f503 to your computer and use it in GitHub Desktop.
DB transform algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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