Skip to content

Instantly share code, notes, and snippets.

@ippeiukai
ippeiukai / string_to_json_escape_outside_bmp.rb
Created December 8, 2015 06:14
monkey patch to ruby's JSON that escapes chars bigger than 3 bytes in UTF-8
require 'active_support'
require 'active_support/concern'
require 'active_support/core_ext'
require 'active_support/json'
# String#to_json to escape any string outside BMP
module StringToJsonWithEscape4byteUtf8
extend ActiveSupport::Concern
included do
@ippeiukai
ippeiukai / delegated_module_function.rb
Created November 24, 2015 07:51
Module functions on steroid. This allows you to define a set of methods as public module methods and private instance methods while keeping private dependencies private.
# module FooBar
# extend DelegatedModuleFunction
#
# define_delegated_module_functions do
#
# def foo_bar
# 'Foo' + bar
# end
#
# private
@ippeiukai
ippeiukai / io_streaming_response_body.rb
Last active November 25, 2015 09:22
Stream data as a file in Rails as they are written to IO.
class IOStreamingResponseBody
def self.render(options = {}, &block)
instance = new(options)
instance.define_singleton_method :render do |dummy_io|
block.call(dummy_io)
end
instance
end
@ippeiukai
ippeiukai / enumerator_with_position_and_size.rb
Created August 27, 2015 02:14
Add `with_position_and_size` method to Enumerator. Those are quite handy inside a loop.
module EnumeratorWithPositionAndSize
# @yields [original_params, position_and_size]
# @yieldparam position_and_size [(Integer, Integer)] 2-element array of position (first being 1) and size; size may be nil (see Enumerator#size)
# @example
# %w[a b c d e].each.with_position_and_size { |char, (position, size)| puts "#{char} (#{position}/#{size})" }
def with_position_and_size
return to_enum(__method__) unless block_given?
my_size = self.size
self.with_index(1) do |original_params, position|
@ippeiukai
ippeiukai / active_record_relation_exitsts.rb
Last active August 29, 2015 14:27
A hack to make `where(relation.exists)` work in 4.2. See https://github.com/rails/rails/issues/16959 for details of the problem and proposed proper solution.
module ActiveRecordRelationExists
# DANGER this switches ActiveRecord::Relation#exists from delegation to arel to our implementation that returns a String with a twist.
# This achieves the most common usage of #exists before 4.2. Proper fix will be: https://github.com/rails/rails/issues/16959
def exists
SqlStringWithNot.new("EXISTS (#{self.to_sql})")
end
class SqlStringWithNot < String
@ippeiukai
ippeiukai / sequel_bulk_update.rb
Last active August 29, 2015 14:24
Bulk update some rows with different values. (for Sequel)
module SequelBulkUpdate
class << self
# NOTE assumes the relation is simple
#
# @param relation [Sequel::Dataset] scope of update
# @param values [Array<Hash{Symbol=>_},#to_h>] values of each row required for updating
# @param where_columns [Array<Symbol>] columns used to identify the target row
# @param set_columns [Array<Symbol>] columns to update
@ippeiukai
ippeiukai / sequel_each_in_batches.rb
Last active March 26, 2024 16:01
ActiveRecord's find_each and find_in_batches ported to Sequel. Sequel's paged_each is not practical when converting large data due to its use of transaction and offset. (Special thanks to @nomuson for working out the primary_keys_expr logic together.)
# ActiveRecord's find_each and find_in_batches ported to Sequel.
# Sequel's paged_each is not practical when converting large data due to its use of transaction and offset.
#
# Usage:
#
# SequelEachInBatches.find_each(dataset, keys) { |record| ... }
#
# It can also monkey patch Sequel::Dataset:
#
# Sequel::Dataset.send(:include, SequelEachInBatches)
@ippeiukai
ippeiukai / use_single_forwardable_with_active_support.rb
Created May 14, 2015 02:29
Have you ever wanted to use def_single_delegator from SingleForwardable but still continue to use `delegate` of ActiveSupport?
module UseSingleForwardableWithActiveSupport
extend ActiveSupport::Concern
included do
original_delegate_method = method(:delegate).unbind if self.respond_to?(:delegate)
extend SingleForwardable
if original_delegate_method.present?
# restore the delegate of ActiveSupport that has been overshadowed by SingleForwardable
define_singleton_method :delegate, original_delegate_method
@ippeiukai
ippeiukai / rails_bulk_update.rb
Last active August 29, 2015 14:18
bulk update of records in rails with UPDATE SET FROM (VALUES ...) AS WHERE
# NOTE assumes the relation is very very simple
def bulk_update(relation, values, where_columns, set_columns)
return if values.empty?
connection = relation.connection
base_class = relation.base_class
if relation.arel.where_sql.present?
relation_ids = relation.ids
end
# monkey patch for https://github.com/willbryant/columns_on_demand/issues/2
require 'active_record'
require 'columns_on_demand'
module ColumnsOnDemand
module BaseMethods
# COPIED