0

Probably been working on this too long, sloppy design, or both. My issue is I have a model I wish to initialize. The object has like 52 attributes, but I'm only setting a certain ~25 depending on which object I've just scanned. When I scan an object I get the columns and match them up with a hash_map I've created.

Example Hash Map

This just matches the scanned text to their respective attribute name.

hash_map = {"Pizza."=>"pizza_pie","PastaBowl"=>"pasta_bowl","tacos"=>"hard_shell_taco","IceCream"=>"ice_cream","PopTarts"=>"pop_tart"}

What I want to do

menu = RestaurantMenu.new(pizza_pie => var1, pasta_bowl => var2, ...)

My only problem is in my code at the moment I have this...

t.rows.each do |r|
  for i in 0..r.length-1
     #hash_map[t.combined_columns[i]] => r.[i]
     puts "#{hash_map["#{t.combined_columns[i]}"]} => #{r[i]}"
  end
end

the puts line displays what I want, but unsure how to get that in my app properly.

daveomcd
  • 6,367
  • 14
  • 83
  • 137

2 Answers2

0

Here is several ways to fix this:

hash_map = {"Pizza."=>"pizza_pie","PastaBowl"=>"pasta_bowl","tacos"=>"hard_shell_taco","IceCream"=>"ice_cream","PopTarts"=>"pop_tart"}

attributes.each do |attribute, element|
  message.send((attribute + '=').to_sym, hash_map[element])
end

or like this:

class Example
  attr_reader :Pizza, :PastaBowl #...

  def initialize args
    args.each do |k, v|
      instance_variable_set("@#{k}", v) unless v.nil?
    end
  end
end

for more details click here

Community
  • 1
  • 1
Talgat Medetbekov
  • 3,741
  • 1
  • 19
  • 26
0

I ended up doing the following method:

attributes = Hash[]
attributes["restaurant"] = tmp_basic_info.name
attributes["menu_item"] = tmp_basic_info.item_name

t.rows.each do |r|
  for i in 0..r.length-1
     attributes["other"] = t.other_information
     attributes[hash_map[t.combined_columns[i]] = r[i]
  end
  row = ImportMenuItem.new(attributes)
  row.save
end
daveomcd
  • 6,367
  • 14
  • 83
  • 137