Bohn
Bohn

Reputation: 26919

Using proper Ruby structures like arrays and hashes to populate data

To populate some sample data in a Rake task curretnyl I have methods like this:

def create_population_summaries
  PopulationSummary.where(year: 2009).first_or_create(member_count: 12, organization_id: 1)
  PopulationSummary.where(year: 2010).first_or_create(member_count: 5, organization_id: 1)
  PopulationSummary.where(year: 2011).first_or_create(member_count: 99, organization_id: 1)
  PopulationSummary.where(year: 2008).first_or_create(member_count: 52, organization_id: 1)
  PopulationSummary.where(year: 2012).first_or_create(member_count: 30, organization_id: 1)
  PopulationSummary.where(year: 2013).first_or_create(member_count: 25, organization_id: 1)
  PopulationSummary.where(year: 2008).first_or_create(member_count: 46, organization_id: 1)
end

So it means there is a PopulationSummary table that has columns like

member_count
year
organization_id

and we have populated them with the data that boss! has given to me.

Now I want to refactor this in a way that it uses some Ruby structures like hashes, arrays, even arrays of hashes, etc... such that after refactoring my method does NOT include those hand typed data inside the method AND those hand typed data should come from that Ruby structure, hash, etc... still in the method I can hand type the names of the fields of the data base, like year, member_count, etc... but the values for those I want to read from the ruby data structure ..

How do you suggest to write that data structure?

Upvotes: 0

Views: 177

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Just out of curiosity, you may totally separate the meta-programming (business rules, came from the boss) and the population itself:

data = [ {
           'year'=>2009,'members'=>12,'organization_id'=>1
         }, {
           'year'=>2010,'members'=>5,'organization_id'=>1
         }, {
           …
       } ]

And then populate:

data.each do |d| 
  d.inject (PopulationSummary) do |rec, val|
    rec.where val
  end.first_or_create
end

But I’m afraid you gonna hate this hint after a couple of months when the boss will bring a new portion of data.

Upvotes: 1

Oct
Oct

Reputation: 1525

What about something like:

DATA = [[ 2009, 12, 1], 
        [ 2010,  5, 1], 
       ... ]

DATA.each do |d|
  PopulationSummary.where(year: d[0]).first_or_create(member_count: d[1], organization_id: d[2])
end

Upvotes: 1

Igor Serebryany
Igor Serebryany

Reputation: 3331

data = [{'year'=>2009, 'members'=>12}, {'year'=>2010, 'members'=>5}....]

then loop

data.each do |d|
  PopulationSummary.where(year: d['year']).first_or_create(member_count: d['members'], organization_id: 1)   
end

Upvotes: 1

Related Questions