Skip to content

Instantly share code, notes, and snippets.

@jfarmer
Forked from rubyonrailstutor/process_datum
Last active December 16, 2015 10:08
Show Gist options
  • Save jfarmer/5417613 to your computer and use it in GitHub Desktop.
Save jfarmer/5417613 to your computer and use it in GitHub Desktop.
# Slightly better name, bang (!) to indicate side effects
def process_raw_data!
# See:
# http://po-ru.com/diary/rubys-magic-underscore/
# http://po-ru.com/diary/destructuring-assignment-in-ruby/
self.raw_data.each do |date, name, url, cb_url, funding_type, value|
Company.where(name: name).first_or_create(url: url, cb_url: cb_url)
# See: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-c-strptime
Event.where(funding_type: funding_type, date: Date.strptime(date, '%M/%y'), value: value).first_or_create
end
end
@jfarmer
Copy link
Author

jfarmer commented Apr 19, 2013

Re: my comment on Facebook, something like this (danger: this is oogly, funny indentation only to prevent line wraps in this comment)

def process_raw_data!
  raw_data.
  group_by { |_, name, url, cb_url| [name, url, cb_url] }.
  each do |(name, url, cb_url), data|
    company = Company.where(name: name).first_or_create(url: url, cb_url: cb_url)

    data.each do |date, _, _, _, funding_type, value|
      company.
        events.
        where(funding_type: funding_type, date: Date.strptime(date, '%M/%y'), value: value).
        first_or_create
    end
  end
end

You could in principle do

raw_data.group_by { |_, name| Company.where(name: name) }

due to how == works on ActiveRecord::Relation objects, but I don't know a clean way to then get at the URL and callback URLs. You'd either have to attach the data in the group_by key somehow without generating a query, or probe the first entry in the array that's now the value for a particular key.

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