Skip to content

Instantly share code, notes, and snippets.

Avatar
🎩
Working on stuff

Jan Bajena Bajena

🎩
Working on stuff
View GitHub Profile
View stream2.rb
class Loader
def load
Enumerator.new { |main_enum| stream(main_enum) }
end
private
def stream(main_enum)
reader = nil
file_uri.open do |file|
View stream1.rb
# 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 Oct 11, 2019
Using sparse fieldsets in ActiveModelSerializers
View sparse_fieldsets.rb
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 Aug 25, 2019
Retriable requests batch for Google Apps Scripts
View RetriableRequestsBatch.gs
/**
* 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) {
View ams_lazy_relationships.rb
class BaseSerializer < ActiveModel::Serializer
include AmsLazyRelationships::Core
end
class PostSerializer < BaseSerializer
attributes :id, :title
lazy_belongs_to :user
end
View serializer.rb
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
View cache.rb
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
View user_lazy.rb
# 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 Jan 27, 2019
Rails joins
View gist.rb
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
View gist:f58850727f8aeeb107fc24d68cbffef9
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 }