{"id":15412572,"url":"https://github.com/elmassimo/queryable","last_synced_at":"2025-04-14T19:11:32.331Z","repository":{"id":15950806,"uuid":"18693314","full_name":"ElMassimo/queryable","owner":"ElMassimo","description":"❔ Gives your queries a home and avoid tucking scopes inside your models","archived":false,"fork":false,"pushed_at":"2022-02-22T19:11:38.000Z","size":130,"stargazers_count":42,"open_issues_count":0,"forks_count":3,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-14T08:51:36.114Z","etag":null,"topics":["activerecord","design-pattern","mongoid","query","query-objects","rails","ruby"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"nieksand/gokinesis","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ElMassimo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-04-12T01:20:43.000Z","updated_at":"2023-12-08T00:32:15.000Z","dependencies_parsed_at":"2022-08-04T05:15:13.861Z","dependency_job_id":null,"html_url":"https://github.com/ElMassimo/queryable","commit_stats":null,"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ElMassimo%2Fqueryable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ElMassimo%2Fqueryable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ElMassimo%2Fqueryable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ElMassimo%2Fqueryable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ElMassimo","download_url":"https://codeload.github.com/ElMassimo/queryable/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248943456,"owners_count":21186958,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","design-pattern","mongoid","query","query-objects","rails","ruby"],"created_at":"2024-10-01T16:53:44.824Z","updated_at":"2025-04-14T19:11:32.305Z","avatar_url":"https://github.com/ElMassimo.png","language":"Ruby","readme":"Queryable\n=====================\n[![Gem Version](https://badge.fury.io/rb/queryable.svg)](http://badge.fury.io/rb/queryable)\n[![Build Status](https://travis-ci.org/ElMassimo/queryable.svg)](https://travis-ci.org/ElMassimo/queryable)\n[![Test Coverage](https://codeclimate.com/github/ElMassimo/queryable/badges/coverage.svg)](https://codeclimate.com/github/ElMassimo/queryable)\n[![Code Climate](https://codeclimate.com/github/ElMassimo/queryable.svg)](https://codeclimate.com/github/ElMassimo/queryable)\n[![Inline docs](http://inch-ci.org/github/ElMassimo/queryable.svg)](http://inch-ci.org/github/ElMassimo/queryable)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ElMassimo/queryable/blob/master/LICENSE.txt)\n\u003c!-- [![Coverage Status](https://coveralls.io/repos/ElMassimo/queryable/badge.png)](https://coveralls.io/r/ElMassimo/queryable) --\u003e\n\nQueryable is a mixin that allows you to easily define query objects with chainable scopes.\n\n### Scopes\n\nScopes serve to encapsulate reusable business rules, a method is defined with\nthe selected name and block (or proc)\n```ruby\nclass CustomersQuery\n  include Queryable\n\n  scope(:recent) { desc(:logged_in_at) }\n\n  scope :active, -\u003e{ where(status: 'active') }\n\n  scope :favourite_brand do |product, brand|\n    where(\"favourites.#{product}\": brand)\n  end\n\n  def current\n    recent.active\n  end\n\n  def miller_fans\n    favourite_brand(:beer, :Miller)\n  end\nend\n\n\nCustomerQuery.new(shop.customers).miller_fans\n```\n\n### Delegation\n\nBy default most Array methods are delegated to the internal query. It's possible\nto delegate extra methods to the query by calling `delegate`.\n```ruby\nclass CustomersQuery\n  include Queryable\n\n  delegate :update_all, :destroy_all, :exists?\nend\n```\n\n### Delegate and Chain\n\nSometimes you want to delegate a method to the internal query, but continue\nworking with the query object like if you were calling scopes.\n\nYou can achieve that using `delegate_and_chain`, which will delegate the method\ncall, assign the return value as the internal query, and return the query object.\n\n```ruby\nclass CustomersQuery\n  include Queryable\n\n  delegate_and_chain :where, :order_by\nend\n```\n\n## Advantages\n\n* Query objects are easy to understand.\n* You can inherit, mixin, and chain queries in a very natural way.\n* Increased testability, pretty close to being ORM/ODM agnostic.\n\n## Basic Usage\n\nIf you are using Mongoid or ActiveRecord, you might want to try the\n`Queryable::Mongoid` and `Queryable::ActiveRecord` modules that already take\ncare of delegating and chaining most of the methods in the underlying queries.\n\n```ruby\nclass CustomersQuery\n  include Queryable::Mongoid\nend\n\nCustomersQuery.new.where(:amount_purchased.gt =\u003e 2).active.asc(:logged_in_at)\n```\n\nThis modules also include all the optional modules. If you would like to opt-out\nof the other modules you can follow the approach in the [Notes](https://github.com/ElMassimo/queryable#notes) section.\n\n## Advanced Usage\nThere are three opt-in modules that can help you when creating query objects.\nThese modules would need to be manually required during app initialization or\nwherever necessary (in Rails, config/initializers).\n\n### DefaultQuery\nProvides default initialization for query objects, by attempting to infer the\nclass name of the default collection for the query, and it also provides a\n`queryable` method to specify it.\n\n```ruby\nrequire 'queryable/default_query'\n\ndef CustomersQuery\n  include Queryable\n  include Queryable::DefaultQuery\nend\n\ndef OldCustomersQuery \u003c CustomersQuery\n  queryable ArchivedCustomers\nend\n\nCustomersQuery.new.queryable == Customer.all\nOldCustomersQuery.new.queryable == ArchivedCustomers.all\n```\nIf you want to use common base objects for your queries, you may want want to\ndelay the automatic inference:\n\n```ruby\nclass BaseQuery\n  include Queryable\n  include Queryable::DefaultQuery\n\n  queryable false\nend\n\nclass CustomersQuery \u003c BaseQuery\nend\n\nCustomersQuery.new.queryable == Customer.all\n```\n\n### DefaultScope\nAllows to define default scopes in query objects, and inherit them in query\nobject subclasses.\n\n```ruby\nrequire 'queryable/default_scope'\n\ndef CustomersQuery\n  include Queryable\n  include Queryable::DefaultScope\n  include Queryable::DefaultQuery\n\n  default_scope :active\n  scope :active, -\u003e { where(:last_purchase.gt =\u003e 7.days.ago) }\nend\n\ndef BigCustomersQuery \u003c CustomersQuery\n  default_scope :big_spender\n  scope :big_spender, -\u003e { where(:total_expense.gt =\u003e 9999999) }\nend\n\nCustomersQuery.new.queryable == Customer.where(:last_purchase.gt =\u003e 7.days.ago)\n\nBigCustomersQuery.new.queryable ==\nCustomer.where(:last_purchase.gt =\u003e 7.days.ago, :total_expense.gt =\u003e 9999999)\n```\n\n### Chainable\n\nWhile scopes are great because of their terseness, they can be limiting because\nthe block executes in the context of the internal query, so methods, constants,\nand variables of the Queryable are not accessible.\n\nFor those cases, you can use a normal method, and then `chain` it. Chainable\nwill take care of setting the return value of the method as the internal query,\nand return `self` at the end to make the method chainable.\n\n```ruby\nclass CustomersQuery\n  include Queryable\n  include Queryable::Chainable\n\n  chain :active, :recent\n\n  def active\n    where(status: 'active')\n  end\n\n  def recent\n    queryable.desc(:logged_in_at)\n  end\n\n  chain def search(field_values)\n    field_values.inject(queryable) { |query, (field, value)|\n      query.where(field =\u003e /#{value}/i)\n    }\n  end\n\n  def search_in_active(field_values)\n    search(field_values).active\n  end\nend\n\n\nCustomerQuery.new(shop.customers).miller_fans.search_in_current(last_name: 'M')\n```\n\n### Notes\nTo avoid repetition, it's a good idea to create a `BaseQuery` object\nto contain both the modules inclusion, and common scopes you may reuse.\n\n```ruby\nrequire 'queryable/chainable'\nrequire 'queryable/default_scope'\nrequire 'queryable/default_query'\n\ndef BaseQuery\n  include Queryable\n  include Queryable::Chainable\n  include Queryable::DefaultScope\n  include Queryable::DefaultQuery\n\n  # If you want to be concise:\n  include Queryable::DefaultQuery, Queryable::DefaultScope, Queryable::Chainable, Queryable\n\n  queryable false\n\n  scope :recent, -\u003e{ where(:created_at.gt =\u003e 1.week.ago) }\nend\n\ndef CustomersQuery \u003c BaseQuery\n...\nend\n```\n\n## Testing\n\nYou can check the [specs](https://github.com/ElMassimo/queryable/tree/master/spec) of the project\nto check how to test query objects without even having to require the ORM/ODM, or\nyou can test by requiring your ORM/ODM and executing queries as usual.\n\n## RDocs\n\nYou can view the **Queryable** documentation in RDoc format here:\n\nhttp://rubydoc.info/github/ElMassimo/queryable/master/frames\n\n\nLicense\n--------\n\n    Copyright (c) 2014 Máximo Mussini\n\n    Permission is hereby granted, free of charge, to any person obtaining\n    a copy of this software and associated documentation files (the\n    \"Software\"), to deal in the Software without restriction, including\n    without limitation the rights to use, copy, modify, merge, publish,\n    distribute, sublicense, and/or sell copies of the Software, and to\n    permit persons to whom the Software is furnished to do so, subject to\n    the following conditions:\n\n    The above copyright notice and this permission notice shall be\n    included in all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felmassimo%2Fqueryable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Felmassimo%2Fqueryable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felmassimo%2Fqueryable/lists"}