[verb ます-stem] + がけに [verb ます-stem] + がけの + [noun]
Typically used with movement/transition verbs (行く、帰る、出る、通る、入る, etc.)
The grammar pattern がけに is used to express doing something on the way to or from somewhere, or in the process of doing something. It attaches to the verb stem (ます-stem) of verbs that indicate movement or transition, such as いく行く, かえる帰る, でる出る, とおる通る, and はいる入る.
The structure is: V[ます-stem] + がけに
This pattern indicates that the action described in the main clause happens incidentally or as an additional action while the speaker is in the course of doing the verb before がけに.
がけに emphasizes that the action occurs as part of or incidental to the movement or transition described by the verb. The secondary action is often something done casually, conveniently, or by chance.
It is most naturally used with movement verbs. You will rarely see it with verbs that do not involve physical movement or departure/arrival.
The particle に can sometimes be replaced with の to modify a noun:
While ついでに means "while you're at it" and focuses on taking advantage of an opportunity to do something extra, がけに focuses more specifically on the transitional moment of going somewhere or leaving. がけに is also more limited in the verbs it can attach to.