Pergunta de entrevista da empresa Synup

It's a question from Ruby on Rails. There is a table named countries(id, name, code) and it contains records like [{1, India, In}, {2, China, Cn}]. Now if someone wants to do Country.India, it should return the corresponding code of that particular record. In the above mentioned case it will be 'In'. How will you implement it?

Resposta da entrevista

Sigiloso

20 de ago. de 2019

def method_missing(method_name, *args) if country = Country.find_by(name: method_name.to_s) country.code else super end end