Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/p-lambert/hayrick
Query Objects without a hitch.
https://github.com/p-lambert/hayrick
query-builder
Last synced: 3 months ago
JSON representation
Query Objects without a hitch.
- Host: GitHub
- URL: https://github.com/p-lambert/hayrick
- Owner: p-lambert
- License: mit
- Created: 2016-08-03T22:36:38.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2016-08-04T21:06:20.000Z (over 8 years ago)
- Last Synced: 2024-08-30T20:49:40.421Z (5 months ago)
- Topics: query-builder
- Language: Ruby
- Size: 10.7 KB
- Stars: 6
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
## Hayrick
*Query Objects without a hitch.*---
[![Build Status](https://travis-ci.org/p-lambert/hayrick.svg?branch=master)](https://travis-ci.org/p-lambert/hayrick)
[![Gem Version](https://badge.fury.io/rb/hayrick.svg)](https://badge.fury.io/rb/hayrick)`Hayrick` lets you easily create
[Query Objects](http://martinfowler.com/eaaCatalog/queryObject.html), decoupling
your data models from querying concerns. It is extremely lightweight, having
less than `100` lines of code and no external dependencies. `Hayrick` currently
supports
[Active Record](https://github.com/rails/rails/tree/master/activerecord) and
[Sequel](https://github.com/jeremyevans/sequel).### Usage
First, add this line to your application's `Gemfile`:
```ruby
gem 'hayrick'
```Then you have just to include the `Hayrick` module and implement a `#base_scope` method:
```ruby
class AlbumCollection
include Hayrickdef base_scope
Album.all # or Album.unscoped depending on your Rails version
end
end
```And that's it! You're now able to perform queries by calling
`AlbumCollection#search`.```ruby
AlbumCollection.new.search(artist: 'Morphine')
=> #, #...]>
```That seems fine, but we usually want to carry out queries using parameters other
than our model fields, right? `Hayrick` provides a simple DSL for adding such
filters:```ruby
class AlbumCollection
include Hayrickfilter :year do |search_relation, year|
search_relation.where('extract(year from released_at) = ?', year)
enddef base_scope
Album.all
end
end
```Notice the `.filter` method receives two parameters:
* a filter name (in this case, `:year`)
* a filter definition which can be either a `Proc` or a block. This callable
object must receive two arguments: the first is the search relation and the
second is the argument for the filter itself. Make sure to always return the
search relation to prevent the filter chain from breaking.```ruby
AlbumCollection.new.search(artist: 'Morphine', year: 1993)
=> #]>
```