Skip to content

Commit

Permalink
Refactor the rows method in the statistics block
Browse files Browse the repository at this point in the history
Divides the rows method to a small public rows method and a private
`row_lines` method. This allows further refactoring without having to
change the tests.

Use a map rather than an each in rows method to make the method
slightly smaller. `each_with_index` has been replaced with
`each_with_object` for the same reason.

The CSV rows are being returned with symbol keys to that `to_sym`
doesn't need to be used in multiple places.

Finally, the row keys and values are being obfuscated.

We can't guarantee what the keys will be named so it's better not to
rely on them.

We're still assuming that each row will have 3 columns:

- x-axis value
- variable / line name
- y-axis value
  • Loading branch information
leenagupte committed Oct 18, 2024
1 parent 692ee73 commit 0f9111c
Showing 1 changed file with 23 additions and 22 deletions.
45 changes: 23 additions & 22 deletions app/models/block/statistics.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,30 +25,12 @@ def x_axis_keys
end

def rows
lines = {}
rows = []

csv_rows.each_with_index do |row, _i|
if lines.key?(row["variable"].to_sym)
lines[row["variable"].to_sym][:values] << row["value"].to_i
else
lines[row["variable"].to_sym] = {
label: row["Date"],
values: [
row["value"].to_i,
],
}
end
end

lines.each_key do |key|
rows << {
row_lines.map do |key, value|
{
label: key.to_s,
values: lines[key][:values],
values: value[:values],
}
end

rows
end

def data_source_link
Expand All @@ -57,8 +39,27 @@ def data_source_link

private

def row_lines
csv_rows.each_with_object({}) do |row, lines|
label = row.keys.first
variable_name = row.values.second
value = row.values.last
if lines.key?(variable_name)
lines[variable_name][:values] << value.to_i
else
lines[variable_name] = {
label:,
values: [
value.to_i,
],
}
end
end
end

def csv_rows
CSV.read(csv_file_path, headers: true).map(&:to_h)
rows = CSV.read(csv_file_path, headers: true).map(&:to_h)
rows.each(&:deep_symbolize_keys!)
end

def csv_file_path
Expand Down

0 comments on commit 0f9111c

Please sign in to comment.