There isn't a general rule. Most of the foreign words have a defined grammatical gender in Italian – although for some of them both are acceptable or their gender is still debated: e.g. font, emoji – but there is not an universal mechanism for its assignment.
According to this post by the Accademia della Crusca, the gender gets assigned most of the time from a hyperonym ("la spider" since spider is one kind of "automobile", which is feminine), or from an Italian term that is or is perceived as the closest translation. However many foreign words don't follow these criteria.
Note that if a noun refers to a person, it will usually take the grammatical gender of whom it refers to.
See also this essay by Treccani.