0

I'm looking to take some yml :

My Random Name of a Topic:
  Color:
    Brown
    Blue
    Green
  Style:
    Thin
    Fat

And I'd like to make a Topic object, and an Item object for all the words in Type and Style combined.

Each of those words will have a type attribute, that will say if its a style or color

Topics have a HABTM with Items, so I would also like to build this connection as well.

But not to ask someone to plow through a huge answer, I'm merely looking at the best way to parse this yaml :

task glass_full_of_yaml: :environment do
  File.open(Rails.root + 'lib/words/glass_full_of.yml', 'r') do |file|
    YAML::load(file).each do |record|
      debugger
      # Item.create!(type: record, name: record)
    end
  end
end

If all my topics are named differently, how can I select its nested attributes and create Item objects out of them?

Trip
  • 26,756
  • 46
  • 158
  • 277

1 Answers1

2

Quick and dirty:

YAML::load(file).each do |topic, item_types|
  Topic.create! :name => topic, :items => item_types.map { |type, names|
    names.split(' ').map { |name|
      Item.new :type => type, :name => name
    }
  }.flatten
end
Tanzeeb Khalili
  • 7,324
  • 2
  • 23
  • 27