In a project I had troubles triying to install mysql2 gem with a older version of mariadb installed via homebrew.
the solution is to send the path of the installation.
gem install mysql2 -- --with-mysql-config=$(brew --prefix mariadb@10.2)/bin/mysql_config