Skip to content

Instantly share code, notes, and snippets.

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
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
@ippeiukai
ippeiukai / sequel_abstract_model.rb
Last active November 25, 2015 09:47
Monkey patch to Sequel (http://github.com/jeremyevans/sequel) that lets you cleanly create an abstract model.
require 'sequel/model'
module Sequel
class << self
# abstract model needs to avoid inherited callback
# (see https://groups.google.com/forum/#!msg/sequel-talk/OG5ti9JAJIE/p1iqO57cwqwJ)
# MyAbstractModel = Sequel.new_abstract_model do
# # ... your common stuff ...
module TwoPlusTwoIsFive
def self.included(base)
base.class_exec do
alias_method :plus_without_two_plus_two_is_five, :+
private :plus_without_two_plus_two_is_five
alias_method :+, :plus_with_two_plus_two_is_five
public :+
end
end
@ippeiukai
ippeiukai / sequel_sqlite_readonly.rb
Created December 19, 2013 04:32
Monkey patch to Sequel (http://github.com/jeremyevans/sequel) that allows it to optionally open a SQLite database in readonly mode
# coding: utf-8
require 'sequel/adapters/sqlite'
# monkey patch to optionally open database in read-only mode
class ::Sequel::SQLite::Database
# [Copied] from sequel-4.5.0/lib/sequel/adapters/sqlite.rb
def connect(server)
opts = server_opts(server)
@ippeiukai
ippeiukai / maybe.rb
Created July 30, 2013 12:04
[Joke] true, false, and ... maybe for Ruby
class MaybeClass < DelegateClass(FalseClass)
LIKELIHOOD = 0.4
def initialize
super(rand < LIKELIHOOD)
end
def ==(obj)
obj.class == self.class
@ippeiukai
ippeiukai / faster_fixture_loading.rb
Last active December 18, 2015 09:59
A monkey patch that speeds up fixture loading of Rails 3.2. The speed up in my case was by five-fold (with ``time rake db:fixtures:load``), quite significant if you have a large set of fixtures and load them regularly.
# for Rails 3.2.12
# loads fixtures a lot faster
require 'active_record/fixtures'
class ActiveRecord::Fixtures
# based on activerecord-3.2.12/lib/active_record/fixtures.rb l.462
# modified lines are marked CHANGED
def self.create_fixtures(fixtures_directory, table_names, class_names = {})
table_names = [table_names].flatten.map { |n| n.to_s }