Skip to content

Instantly share code, notes, and snippets.

@sixtyfive
Last active May 12, 2020 17:48
Show Gist options
  • Save sixtyfive/4e6fc502d851905766968011289b1c2c to your computer and use it in GitHub Desktop.
Save sixtyfive/4e6fc502d851905766968011289b1c2c to your computer and use it in GitHub Desktop.
# - You're iterating over `@catalog['entries']` twice? Both `e` and `entry`.
# - If you know the key exists, consider #fetch.
REF_ROW = ['ba_partitioning', 0, 'belongs_to_or_copy_of', 0, 'ba_xlsx_row'].freeze
def link_interconnected_entries
@catalog['entries'].each do |entry|
ref_entry = nil
if ref = entry.dig(*REF_ROW)
@catalog['entries'].each{|e| ref_entry = e if e['ba_xlsx_row'].to_i == ref.to_i}
puts "#{ref} points to #{ref_entry['thing']}."
# do actual stuff here
end
rescue NoMethodError
warn "Invalid reference!"
# put that warning back into @catalog['entries']
end
end
@havenwood
Copy link

# frozen_string_literal: true

REF_ROW = ['ba_partitioning', 0, 'belongs_to_or_copy_of', 0, 'ba_xlsx_row'].freeze

def link_interconnected_entries
  entries = @catalog.fetch('entries')
  entry_refs = entries.map { |entry| entry.dig(*REF_ROW) }.compact
  entry_refs.each do |ref|
    ref_entry = entries.find do |entry|
      entry.fetch('ba_xlsx_row').to_i == ref.to_i
    end

    unless ref_entry
      warn 'Warning: invalid reference!'
      next
    end

    puts "#{ref} points to #{ref_entry.fetch('thing')}."
  end
end

Then extract method refactor. :)

@sixtyfive
Copy link
Author

sixtyfive commented May 12, 2020

Okay, changed it to this now:

REF_ROW = ['ba_partitioning', 0, 'belongs_to_or_copy_of', 0, 'ba_xlsx_row'].freeze
def entry_refs(entries)
  entries.map{|e| e.dig(*REF_ROW)}.compact
end

ROW = 'ba_xlsx_row'.freeze
def ref_entry(entries, ref)
  entries.find{|e| e.fetch(*ROW).to_i == ref.to_i}
end

def link_interconnected_entries
  entries = @catalog.fetch('entries')
  entry_refs(entries).each do |ref|
    ref_entry = ref_entry(entries, ref)
    (warn 'Invalid reference!'; next) unless ref_entry # replace with actual code
    puts "#{ref} points to #{ref_entry.fetch('thing')}" # replace with actual code
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment