QueryMagic
Query object helper for ActiveRecord
Installation
TODO: Replace UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
Install the gem and add to the application's Gemfile by executing:
$ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
If bundler is not being used to manage dependencies, install the gem by executing:
$ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
Usage
Use QueryMagic::Query to define a query object to write readable queries. For instance if you have a BlogPost
model you can use a subclass of QueryMagic::Query
to help create some methods:
class BlogPostQuery < QueryMagic::Query
default_relation { Item.all }
define_static_filter :published_recently,
column: 'published_at',
arel_selector: 'gt',
val: 1.week.ago.to_date
define_join_filter :with_tags,
join_name: 'tags',
join_class: 'Tag',
column: 'name'
def medium_length
where("length(content) BETWEEN 500 AND 10000")
end
def short_posts_order
order("length(content) ASC, author ASC, updated_at DESC")
end
end
results = BlogPostQuery.new
.with_tags(["ruby", "rails"])
.where(author: "Magic Blogger")
.published_recently
.medium_length
.short_posts_order
.to_a
Development
After checking out the repo, run bin/setup
to install dependencies. You can also run bin/console
for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To release a new version, update the version number in version.rb
, and then run bundle exec rake release
, which will create a git tag for the version, push git commits and the created tag, and push the .gem
file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://0xacab.org/calyx/gems/query_magic.