Dynamically apply named scopes to Rails resources based on incoming controller parameters for flexible filtering.
HasScope is a Ruby gem that maps incoming controller parameters to named scopes in ActiveRecord models. It provides a clean, declarative way to filter resources dynamically, making it easier to build flexible APIs and search interfaces without cluttering controller logic.
Ruby on Rails developers building APIs, search interfaces, or admin panels that require dynamic filtering of ActiveRecord resources based on URL parameters.
Developers choose HasScope for its convention-over-configuration approach that keeps filtering logic concise and declarative in controllers, while offering full flexibility for custom implementations via blocks and standalone usage in POROs.
Map incoming controller parameters to named scopes in your resources
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.
Automatically maps URL parameters to ActiveRecord scopes with type checking, reducing boilerplate code. For example, declaring `has_scope :featured, type: :boolean` cleanly handles boolean filters without manual parsing.
Supports rich options like `:type`, `:only`, `:except`, `:default`, and blocks for custom logic, allowing conditional and complex scope applications. The README shows how to use `:if` and `:unless` for fine-grained control.
Can be included in plain Ruby objects outside Rails controllers, enabling use in query objects or services. The example demonstrates creating a `GraduationsSearchQuery` class for encapsulated filtering logic.
Provides `current_scopes` to track applied scopes during a request, useful for debugging or view logic. The README illustrates how it returns a hash of scope names and values after filtering.
Only works with ActiveRecord models, making it unsuitable for applications using other ORMs or data sources, which limits its versatility in polyglot persistence setups.
Boolean parsing has nuances: `?active` alone is not considered true (requires `?active=true` or `?active=1`), which can be non-intuitive and lead to bugs if developers expect different behavior.
Passing strings to `:if` and `:unless` options is deprecated and will be removed, as noted in the README, potentially causing breaking changes in future versions and requiring code updates.
While blocks allow custom logic, they can make code less declarative and more verbose, as seen in the keyword arguments example where manual scope calling is needed, reducing the gem's simplicity.