Skip to content

Instantly share code, notes, and snippets.

View mikekreeki's full-sized avatar

Michal Krejčí mikekreeki

View GitHub Profile
" Vim color scheme based on http://github.com/jpo/vim-railscasts-theme
"
" Name: mikekreeki.vim
" Maintainer: Michal Krejčí
" License: MIT
set background=dark
hi clear
if exists("syntax_on")
syntax reset
{
address: {
location1: 'Some location'
},
land_line_phone: '333333333',
monthly_income: '450'
}
class Client
belongs_to :country, counter_cache: true
def country_code=(country_code)
self.country = Country.by_code country_code
end
end
@mikekreeki
mikekreeki / macros.rb
Created January 14, 2015 12:04
Action macro for RSpec (very useful for controller specs)
module RSpec
module Macros
def action(&block)
before do |example|
if example.metadata.fetch(:action, true)
instance_eval(&block)
end
end
end
end
module ActiveInteraction
class ObjectFilter < Filter
register :object
def cast(value)
@klass ||= klass
if matches?(value)
value
else
@mikekreeki
mikekreeki / active_interaction.rb
Last active August 29, 2015 14:05
One big reason to pick ActiveInteraction to implement Command pattern in Rails apps over rolling you own solution using Virtus and ActiveModel::Model
class Foo < ActiveInteraction::Base
string :bar
# additional validations
# validates :bar, ...
def execute
unless do_something
errors.add :bar, 'is not cool'
end
@mikekreeki
mikekreeki / email_listener.rb
Created June 27, 2014 14:22
How to use ActiveRecord::Callbacks with clear separation of responsibilities
class EmailListener
def user_created(user)
UserMailer.welcome_email(user).deliver
end
end
class PostsController < ApplicationController
respond_to :json # default to Active Model Serializers
def index
respond_with Post.all
end
def show
respond_with Post.find(params[:id])
end
@mikekreeki
mikekreeki / tap.rb
Created January 15, 2013 18:29
Smarter Object#tap
class Object
alias :old_tap :tap
def tap(&block)
old_tap do
if block.arity == 0
instance_eval &block
else
block.(self)
@mikekreeki
mikekreeki / require.rb
Created April 26, 2012 15:07
multiple require refactorings
require 'nokogiri'
require 'active_support'
require 'benchmark'
# equal to...
list = ['nokogiri', 'active_support', 'benchmark']
## never use `for` cycle (unless you know exactly why), it's considered a bad practice,
## you save one method call since `for` calls `each` method internally anyway