Skip to content

Instantly share code, notes, and snippets.

def log(message)
delayed_message = proc{"#{Time.now.strftime("%T.%L")} pid:#{Process.pid} cache_id:#{@cache_id} #{message}"}
Rails.logger.error(" #{incr} #{delayed_message.()}")
res = yield
Rails.logger.error(" #{decr} #{delayed_message.()}")
res
end
def incr
@nesting ||= 0
@torkale
torkale / cache_mutex.rb
Created May 21, 2012 12:13
Distributed lock using rails cache
require 'active_support/all'
require 'timeout'
class CacheMutex
INTERVAL = 0.01
TIMEOUT = 20
def initialize(name)
@name = name
@have_lock = false
@torkale
torkale / Gemfile
Created May 9, 2012 09:23
add vcr and fakeweb to gemfile
group :test do
gem 'vcr'
gem 'fakeweb'
end
@torkale
torkale / .gitignore
Created May 9, 2012 09:07
Instruct git to ignore vcr cassettes
spec/cassettes*
@torkale
torkale / vcr_spec.rb
Created May 9, 2012 09:04
describe and context with vcr
describe "group", :vcr do
...
end
context "other group", :vcr do
...
end
@torkale
torkale / spec_helper.rb
Created May 9, 2012 09:00
VCR in spec helper
require 'vcr'
...
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :fakeweb
c.configure_rspec_metadata!
end
RSpec.configure do |config|
...
@torkale
torkale / user.rb
Created April 24, 2012 06:20
DRY using define
class User < ActiveRecord::Base
STATUS = { :active => 1, :inactive => 2, :pending => 3, :announce => 4, :curator => 5 }
STATUS.each do |k, v|
define_singleton_method(k) do
where(:status => v)
end
end
end
@torkale
torkale / user.rb
Created April 24, 2012 06:18
repeating singleton methods
class User < ActiveRecord::Base
STATUS = { :active => 1, :inactive => 2, :pending => 3, :announce => 4, :curator => 5 }
def self.active; where(:status => STATUS[:active]); end
def self.inactive; where(:status => STATUS[:inactive]); end
def self.pending; where(:status => STATUS[:pending]); end
def self.announce; where(:status => STATUS[:announce]); end
end
@torkale
torkale / user.rb
Created April 24, 2012 06:06
repeating scopes
class User < ActiveRecord::Base
STATUS = { :active => 1, :inactive => 2, :pending => 3, :announce => 4, :curator => 5 }
scope :active, where("status = #{STATUS[:active]}")
scope :inactive, where("status = #{STATUS[:inactive]}")
scope :pending, where("status = #{STATUS[:pending]}")
scope :announce, where("status = #{STATUS[:announce]}")
end
@torkale
torkale / download_latest_backup.rb
Created April 15, 2012 07:49
download latest backup from S3
require 'rubygems'
require 'fog'
connection = Fog::Storage.new(:provider => 'AWS')
directory = connection.directories.find{|dir| dir.key == ENV['BUCKET_KEY']}
file = directory.files.last
File.open ENV['BACKUP_FILE'], 'w' do |backup|
backup << file.body
end