Skip to content

Instantly share code, notes, and snippets.

@samuelkadolph
samuelkadolph / _form.html.erb
Created July 28, 2011 19:21
+ button to add nested object to fields_for & accepts_nested_attributes
<%= form_for(@foo) do |f| %>
<%= f.fields_for :bars do |b| %>
<%= b.text_field :name %>
<% end %>
<%= f.submit "+", :name => "actions[add_bar]" %>
<div class="actions">
<%= f.submit %>
</div>
@samuelkadolph
samuelkadolph / gist:1093632
Created July 19, 2011 20:33
Use RVM and TextMate
defaults write com.macromates.textmate OakShellVariables -array-add "{ enabled = 1; variable = TM_RUBY; value = '$(which rvm-auto-ruby)'; }"
@samuelkadolph
samuelkadolph / routes.rb
Created July 6, 2011 18:04
Redirect http traffic to https from routes.rb only
constraints :protocol => "https" do
resources :gizmos
end
constraints :protocol => "http" do
match "/(*path)" => redirect { |p, r| URI(r.url).tap { |u| u.scheme = "https" }.to_s }
end
@samuelkadolph
samuelkadolph / dups.rb
Created June 23, 2011 05:25
Find duplicate files, works best on jruby for true multithreading
require "digest/md5"
require "thread"
files = Dir["**/*"]
files_mutex = Mutex.new
hashes = Hash.new { |h, k| h[k] = [] }
hashes_mutex = Mutex.new
processors = `sysctl -n hw.logicalcpu`.to_i
processors.times.map do |i|
@samuelkadolph
samuelkadolph / pipes.rb
Created June 21, 2011 21:45
2 duplex pipes in ruby
require "socket"
a, b = Socket.pair(:INET, :STREAM)
a << "abc\n"
b.gets # => "abc\n"
b << "abc\n"
a.gets # => "abc\n"
resources :things, :glob_id => true
var fs = require("fs");
var http = require("http");
var https = require("https");
var express = require("express");
var app = express.createServer();
var httpsOptions = {
key: fs.readFileSync(process.env.HOME + "/localhost-key.pem"),
cert: fs.readFileSync(process.env.HOME + "/localhost-cert.pem")
class InlineFormsController < ApplicationController
def self.cancan_enabled?
return @cancan_enabled if defined?(@cancan_enabled)
@cancan_enabled = begin
::Ability && true
rescue NameError
false
end
end
@samuelkadolph
samuelkadolph / tattletail.rb
Created January 12, 2011 16:55
Ruby script to parse a rails log file and gist the error and source files.
require "cgi"
require "net/http"
require "uri"
def error(msg, code = -1)
puts(msg)
exit(code)
end
def add_gist_file(gist, number, name, content, ext = File.extname(name))
@samuelkadolph
samuelkadolph / application_model.rb
Created December 29, 2010 23:08
How to safely add a class method to your models that affects attributes
class ApplicationModel < ActiveRecord::Base
self.abstract_class = true
class_attribute :formatted_attributes_options
self.formatted_attributes_options = {}
def self.formatted_attributes(*attributes)
options = attributes.extract_options!
attributes.each do |attribute|
formatted_attributes_options[attribute] = options