I need to validate a value with data from an external API. The easiest way would be to add a validation rule in my model, call the external API and do my check.

But it feels very dirty to call an API within my model. (Also a lot of specs would fail due to missing api call mock).

What other options do I have within the normal rails stack?

What other options would I have, given I have a more complex model layer, such as service objects, repositories, etc.

  • What, exactly, do you mean by "normal Rails stack"? Also, what do you mean by "more complex model layer" - things like service objects and repositories are usually implemented as plain old Ruby classes and are frequently used in Rails - there's absolutely nothing special about them, although there are some frameworks that give more structure to them. – Thomas Owens Jun 25 '19 at 11:53
  • By "normal rails stack" I mean Model, View, Controller classes. Nothing more. So how would I implement this API check? Within my model? Within my controller? There are not many options. When I have a more sophisticated stack like service objects, form objects I have more options to implement this validation. e.g. I could implement the validation within my service objects. – Nghi93 Jun 25 '19 at 13:55
  • I think you're operating on some false assumptions. Why do you believe that you need to stick to only models, views, and controllers? I have never worked in a Rails application more than the most trivial that stuck to those three constructs. If you're constraining yourself artificially, you aren't going to have a good solution to this problem that will be robust in a production environment. – Thomas Owens Jun 25 '19 at 14:11
  • I do not restrict myself, I am just asking for different options I have with a "normal" rails stack and with a complex one. – Nghi93 Jun 26 '19 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.