Skip to content

Instantly share code, notes, and snippets.

@harlow
harlow / user.rb
Last active November 16, 2023 15:13
Extract a validator in Rails. Zip code validation.
# app/models/user.rb
class User < ActiveRecord::Base
validates :zip_code, presence: true, zip_code: true
end
class TaskCompletion
include ActiveModel::Model
attr_accessor :task, :complete
validates :complete, inclusion: { in: [true, false] }
def self.for_task(task, params={})
new(params).tap do |completion|
completion.task = task
end
{
"_links": {
"self": { "href": "/orders" },
"next": { "href": "/orders?page=2" },
"find": { "href": "/orders{?id}", "templated": true }
},
"_embedded": {
"orders": [{
"_links": {
"self": { "href": "/orders/123" },
#!/bin/bash
# from here: http://www.codingsteps.com/install-redis-2-6-on-amazon-ec2-linux-ami-or-centos/
# and here: https://raw.github.com/gist/257849/9f1e627e0b7dbe68882fa2b7bdb1b2b263522004/redis-server
###############################################
# To use:
# wget https://raw.github.com/gist/2776679/04ca3bbb9f085b192f6aca945120fe12d59f15f9/install-redis.sh
# chmod 777 install-redis.sh
# ./install-redis.sh
###############################################
echo "*****************************************"
backend default {
.host = "127.0.0.1";
.port = "8000";
}
# We go BACK to varnish to get it to generate an ESI template that
# generates a JSON-P response.
backend jsonp_template_backend {
.host = "127.0.0.1";
.port = "8070";
@harlow
harlow / app.rb
Last active December 30, 2015 17:59
Refactoring ideas for https://github.com/JamesChevalier/hashtagged/blob/master/app.rb#L17-L27. Extract an object. Encapsulate the interaction with the Twitter client. Extract named methods for looping logic.
require 'sinatra'
require 'twitter'
class App < Sinatra::Base
get '/' do
erb :index
end
post '/hashtags' do
@user_name = user_name
require 'spec_helper'
describe UsersController, '#create' do
let(:group_id) { double(:group_id) }
let(:group) { double(:group) }
let(:user) { double(:user) }
before do
Group.should_receive(:find).with(group_id).and_return(group)
group.should_receive(:create_user).with(attributes).and_return(users)
@harlow
harlow / purchase.rb
Last active January 1, 2016 15:09
Example of using Casting Gem.
class Purchase
include ActiveModel::Model
attr_accessor :customer # + other order related fields..
# some validations
def save
if valid?
charge_customer && create_order
@harlow
harlow / cache_control.rb
Created April 16, 2014 22:20
Rails 4 cache_control headers
def set_cache_control_headers(max_age = 1.second.to_s)
if request.method == "GET"
request.session_options[:skip] = true
response.cache_control[:public] = true
response.cache_control[:extras] = ['no-cache']
response.headers['Surrogate-Control'] = "max-age=#{max_age}"
end
end