Introducing Priora: An Object Prioritization Utility Gem for Ruby

Eliav Lavi
Sep 17, 2018 · 7 min read
Image for post
Image for post
class Post
attr_reader :author, :like_count, :is_sponsored

def initialize(author:, like_count:, is_sponsored:)
@author = author
@like_count = like_count
@is_sponsored = is_sponsored
end
end

Comes in Priora

Priora in Action

low_like_count_sponsored = Post.new(author: 'Jay C.',
like_count: 10, is_sponsored: true)
high_like_count_unsponsored = Post.new(author: 'Aaron R.',
like_count: 90, is_sponsored: false)
high_like_count_sponsored = Post.new(author: 'Don Y.',
like_count: 90, is_sponsored: true)
unprioritized_array = [high_like_count_unsponsored, low_like_count_sponsored, high_like_count_sponsored]prioritized_array =  [high_like_count_sponsored, high_like_count_unsponsored, low_like_count_sponsored]Priora.prioritize(unprioritized_array, by: [:like_count, :is_sponsored]) == prioritized_array
=> true
Image for post
Image for post
https://pixabay.com/en/ropes-ship-barge-sea-nautical-2151683/

Fixed Class Priorities

class Post
include Priora
prioritize_by :like_count, :is_sponsored
attr_reader :author, :like_count, :is_sponsored def initialize(author:, like_count:, is_sponsored:)
@author = author
@like_count = like_count
@is_sponsored = is_sponsored
end
end
Priora.prioritize(unprioritized_array) == prioritized_array
=> true

Advantages Over Using Custom Enumerable#sort

unprioritized_array.sort { |a, b|
[a.like_count, a.is_sponsored ? 1 : 0] <=>
[b.like_count, b.is_sponsored ? 1 : 0] }.reverse == prioritized_array
=> true

Reverse Sorting, Extended: An Agenda

Directional Priorities

Priora.prioritize(unprioritized_array, by: [[like_count: :asc], :is_sponsored])
=> [low_like_count_sponsored, high_like_count_sponsored, high_like_count_unsponsored]

Implicit Conversions

Priora.configuration.add_conversion_lambda(String, lambda { |value| value.length })
Priora.configuration.remove_conversion_lambda(String)

Image for post
Image for post

Ruby Inside

Ruby articles and posts

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store