Skip to content

Instantly share code, notes, and snippets.

@moro
moro / sql2csv.rb
Created March 11, 2020 03:14
思った以上に簡単にかけた便利コマンド
require 'csv'
require 'sequel'
def sql_to_csv(sql, db: Sequel.connect(ENV['DATABASE_URL']))
rel = db[sql]
CSV.generate('', force_quotes: ENV['NO_QUOTE'].nil?) do |csv|
csv << rel.columns
rel.each {|row| csv << row.values }
end
module Constructor
def constructor(*names)
define_method(:initialize) do |*args|
names.zip(args).each do |name, value|
instance_variable_set("@#{name}", value)
end
end
end
end
@moro
moro / gist:7112972
Created October 23, 2013 05:20
場当たり的なコールバック回避
class Foo < ActiveRecord::Base
after_save :do_something, unless: :other_situation?
class << self
def other_situation
begin
Thread.current[:other_situation] = true
yield
ensure
Thread.current[:other_situation] = nil
@moro
moro / doublet.rb
Created June 18, 2013 08:24
Syntax suger for defining double.
module Doublet
def doublet(name, &block)
let(name) { double.tap(&block) }
end
def doublet!(name, &block)
let!(name) { double.tap(&block) }
end
end
@moro
moro / gist:5755105
Created June 11, 2013 07:48
Coffee script like constructor definition
module CoffeeConstructor
def constructor(*ivars)
define_method :initialize do |*args|
raise(ArgumentError) unless ivars.size == args.size
ivars.zip(args).each do |ivar, val|
instance_variable_set(ivar, val)
end
end
end
module Censorable
extend ActiveSupport::Concern
class MonitorRequestFailed < RuntimeError
...
end
included do
has_many :monitor_requests, as: :entity, dependent: :destroy
@moro
moro / gist:5596366
Created May 17, 2013 01:34
retriable
module Retriable
class RepeatedError < RuntimeError
def initialize(max, *args)
@errors = []
@max = max
super(*args)
end
def <<(e)
@errors << e
['foo', 'bar'].inject(Paste.scoped) {|rel, tag|
rel.where(id: Tagging.joins(:tag).select(:paste_id).where('tags.name = ?', tag))
}.to_sql
# =>
# SELECT "pastes".*
# FROM "pastes"
# WHERE "pastes"."id" IN (SELECT paste_id FROM "taggings" INNER JOIN "tags" ON "tags"."id" = "taggings"."tag_id" WHERE (tags.name = 'foo'))
# AND "pastes"."id" IN (SELECT paste_id FROM "taggings" INNER JOIN "tags" ON "tags"."id" = "taggings"."tag_id" WHERE (tags.name = 'bar'))
#
@moro
moro / unit_test_spec.rb
Created September 19, 2012 02:31
unit_test_spec.rb
class A
def foo(num)
%w[one two three][num - 1]
end
end
describe A do
describe "#foo" do
RSpec::Matchers.define :do_foo do |args|
match do |instance|
@moro
moro / gist:3088087
Created July 11, 2012 04:48
Hash#nested_fetch
module NestedFetch
def nested_fetch(*keys)
keys.inject(self) do |hash, key|
(v = hash[key]).nil? ? break : v
end
end
end
Hash.class_eval { include NestedFetch }