Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

View Bajena's full-sized avatar
🎩
Working on stuff

Jan Bajena Bajena

🎩
Working on stuff
View GitHub Profile
class Loader
def load
Enumerator.new { |main_enum| stream(main_enum) }
end
private
def stream(main_enum)
reader = nil
file_uri.open do |file|
# frozen_string_literal: true
require "net/ftp"
class Loader
def load
Enumerator.new { |main_enum| stream(main_enum) }
end
private
@Bajena
Bajena / sparse_fieldsets.rb
Last active October 11, 2019 10:56
Using sparse fieldsets in ActiveModelSerializers
class BaseApiController
def render_json_api(options)
render(
options.merge(included).merge(fields: fields).merge(adapter: :json_api)
)
end
# Allows limiting fields in given resource type's payloads.
# `fields` param is sent as a hash in which:
# - keys are singular or plural resource names (e.g. `accounts` or `account`)
@Bajena
Bajena / RetriableRequestsBatch.gs
Created August 25, 2019 16:23
Retriable requests batch for Google Apps Scripts
/**
* Calls provided HTTP requests batch and retries in case of errors
*
* @param {object} fetchService - service for performing HTTP requests. Defaults to UrlFetchApp provided by Google.
* @param {Array<object>} requests - Array of request param objects
* (https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetchurl-params)
*
* @return {object} RetriableRequestsBatch.
*/
function RetriableRequestsBatch(fetchService, requests) {
class BaseSerializer < ActiveModel::Serializer
include AmsLazyRelationships::Core
end
class PostSerializer < BaseSerializer
attributes :id, :title
lazy_belongs_to :user
end
class PostSerializer < ActiveModel::Serializer
attributes :id, :title
belongs_to :user
def self.lazy_user(post)
BatchLoader.for(post.user_id).batch do |user_ids|
User.where(id: user_ids)
end
end
users = posts.map { |post| post.user_lazy }
users.each { |user| puts "#{user.name}" } # SELECT * FROM users WHERE id IN (1, 2, 3)
users.each { |user| puts "#{user.address}" } # Pobierze użytkowników z cache'u
# app/models/post.rb
def user_lazy
BatchLoader.for(user_id).batch do |user_ids|
User.where(id: user_ids)
end
end
posts = Post.where(id: [1, 2, 3]) # SELECT * FROM posts WHERE id IN (1, 2, 3)
users = posts.map { |post| post.user_lazy }
@Bajena
Bajena / gist.rb
Created January 27, 2019 21:23
Rails joins
Post.joins(:users).where(users: { country_code: 'PL' }).map { |post| post.title }
# SELECT "posts".* FROM "posts" INNER JOIN "users" ON "posts"."user_id" = "users"."id" WHERE "users"."country_code" = $1
posts = Post.where(id: [1, 2, 3]).includes(:user)
# SELECT * FROM posts WHERE id IN (1, 2, 3)
# SELECT * FROM users WHERE id IN (1, 2, 3)
users = posts.map { |post| post.user }