Last Updated: February 25, 2016
· managr

From has_scope to virtus form objects

I was usually using has_scope gem for exposing model scopes to application's controllers. While it's pretty convenient for building simple search filters I was ending up having all the scopes copied from particular models to the corresponding controllers.

To improve that at first I started extracting has_scope calls from controllers to the separate modules implemented in the model classes. Having controller's and model's scopes in one place improved it's management quite a bit.

Still I wasn't quite happy with code duplication and other aspects like parsing search criteria or setting it's default values happening directly in the model.

Decided to introduce form objects to encapsulate all the search criteria. Virtus was very handy for it. Easily allowed to set the default values and simplified parsing controller's params by using custom coercions. I'm now having one liner for parsing the parameters and single scope for search form object.

Thin controllers, domain oriented search objects (single place for defining default values and parsing search criteria), no code duplication. Try virtus!

1 Response
Add your response

I dig that approach, only that the User's byusersearch scope gets really messy, imho.

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post a tip