Frecency
Overview
Frecency is a Ruby on Rails gem that provides a way to sort models based on a combination of frequency and recency, also known as "frecency." This allows for more relevant sorting of records by considering both how often and how recently an item has been accessed or updated.
Installation
To install the frecency
gem, add it to your Gemfile in your Rails application:
gem 'frecency'
Then, run the following command to install the gem:
bundle install
Configuration
Initializer Configuration
You need to configure your frecency gem in an initializer. Create a file named frecency.rb
in your config/initializers
directory:
Frecency.configure do |config|
config.default_frequency_column = :views_count
config.default_recency_column = :updated_at
config.default_custom_frequency_scope = nil
end
Model Configuration
Next, configure the models that you want to utilize frecency sorting. You can do this by adding the necessary configuration to each model. Here’s how you can configure a model:
Basic Configuration
For basic configuration using default settings:
class Product < ApplicationRecord
configure_frecency(
frequency: :views_count,
recency: :updated_at
)
end
Custom Frequency Scope
If you need a custom frequency scope, you can specify it:
class Order < ApplicationRecord
belongs_to :product
configure_frecency(
frequency: :dynamic,
recency: :created_at,
custom_frequency_scope: -> {
select("#{table_name}.*, COUNT(orders.id) as frequency")
.joins(:orders)
.group("#{table_name}.id")
}
)
end
Usage
After configuring the gem, you can use the frecency
method to fetch records sorted by frecency:
Basic Usage
To retrieve top 10 products sorted by frecency:
top_products = Product.frecency(10)
Advanced Usage
You can define more complex configuration and filtering:
class CustomModel < ApplicationRecord
configure_frecency(
frequency: :custom_count,
recency: :last_accessed_at,
custom_frequency_scope: -> {
select("#{table_name}.*, custom_logic() as frequency")
}
)
end
top_records = CustomModel.frecency(20)
Contributing
- Fork the repository on GitHub.
- Clone your forked repository.
- Create a new branch for your feature or bug fix.
- Write tests for your feature or bug fix.
- Make your changes.
- Run RSpec tests (or your preferred test suite).
- Commit your changes and push to your fork.
- Create a pull request on GitHub.
License
This gem is available as open source under the terms of the MIT License.