jeudi 26 janvier 2017

Is there a way to make this code DRY?

I have a Command and Server model which are associated with has_many_and_belongs_to in both model.

I also have commands_servers table which store command_id and server_id.

I have added the commands in the Command table and also server.commands.push(commands) will automatically populate the commands_servers table.

    ["123","456abc", "987jhg"].each do |partnum|
      command = "workworkwork"
      commands = Command.create( name: "command1", partnum: partnum, command: command)      
      ["server1", "server2"].each do |assettag|
        server = Server.find_by_assettag(assettag)
        server.commands.push(commands) 
      end
      command = "playplayplay"
      commands = Command.create( name: "command2", partnum: partnum, command: command)
      ["server3", "server4", "server5"].each do |assettag|
        server = Server.find_by_assettag(assettag)
        server.commands.push(commands)  
      end
    end

So, I was wondering can i refactor the code to make it DRY because i think i am repeating.

Aucun commentaire:

Enregistrer un commentaire