Skip to content

Instantly share code, notes, and snippets.

@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 / 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
module MongoidEmbeddedObjectModification
# Custom field behaves more like an immutable value.
# Your changes to the object obtained with getter method will not take an effect unless you assign it back.
# https://github.com/mongoid/mongoid/issues/3341
def modify(mongoid_doc, field_name)
obj = mongoid_doc.public_send(field_name)
yield obj
mongoid_doc.public_send("#{field_name}=", obj)
end