Project

raspy

0.0
No commit activity in last 3 years
No release in over 3 years
raspy adds a prefetch mechanism to ActiveRecord which is parallel to the ActiveRecord associations.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.12
~> 10.0
~> 3.0

Runtime

< 6.0.0, >= 4.0.0
>= 1.0.5, ~> 1.0
 Project Readme

Raspy

Raspy provides an alternative to define and prefetch associations or relations between ActiveRecord models.

Installation

Add this line to your application's Gemfile:

gem 'raspy'

And then execute:

$ bundle

Or install it yourself as:

$ gem install raspy

Usage

Here is a simple example of using the SQL DSL:

class User < ActiveRecord::Base
  include Rusql
  
  def permissions
    user_permissions = table(:user_permissions)
    
    query = select( distinct( Permission[:name] ) ).
    from( Permission ).
    left_outer_join( user_permissions, user_permissions[:permission_id].equals( Permission[:id] ) ).
    left_outer_join( User, User[:id].equals( user_permissions[:user_id] ) ).
    where( User[:id].equals(self.id) )
    
    Permission.find_by_sql( query.to_s )
  end
end

Here is an advanced example of using the SQL DSL:

class User < ActiveRecord::Base
  extend Rusql
  
  def self.additional_selects
    [
        group_concat( distinct( Permission[:name] ) ).as( :permission_string_list )
    ]
  end
  
  def self.additional_joins
    user_permissions = table(:user_permissions)
    
    [
        left_outer_join( user_permissions, user_permissions[:user_id].equals( User[:id] ),
        left_outer_join( Permission,       Permission[:id].equals( user_permissions[:permission_id] )
    ]
  end
  
  def permissions
    self.permission_string_list.split(",")
  end
  
  def self.fetch(id:)
    selects = [ User[:*].as_selector ]
    selects += User.additional_selects
    
    
    query = select( selects ).
        from( User ).
        where( User[:id].equals(id) ).
        limit( 1 )
        
    User.additional_joins.each do |j|
        query = query.join( j )
    end
    
    User.find_by_sql(query.to_s).first
  end
end

Here's an example for the prefetch

users = User.all.to_a

[users].prefetch({
  permissions: {
    type: "has_and_belongs_to_many",
    klass: Permission,
    foreign_key: "user_id",
    association_foreign_key: "permission_id",
    join_table: "user_permissions",
    association_condition: Permission[:deleted].equals("F")
  }
})

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/sparkymat/raspy. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.