Skip to content

Instantly share code, notes, and snippets.

View thisivan's full-sized avatar

Ivan Torres thisivan

View GitHub Profile
@thisivan
thisivan / create_attributes_accessor_dynamically.rdoc
Created December 14, 2009 19:13
Create Attributes Accessor Dynamically in Ruby

Create Attributes Accessor Dynamically in Ruby

params.each do |key, value|
  self.instance_variable_set("@#{key}", value)
  self.class.send(:define_method, key, proc { self.instance_valiable_get("@#{key}") })
end
@thisivan
thisivan / gist:255456
Created December 13, 2009 15:48
Convert from ERB to HAML
find ./app/views/comments/ -name '*erb' | \
xargs ruby -e 'ARGV.each { |i| puts "html2haml -r #{i} #{i.sub(/erb$/,"haml")}"}' | \
bash

Append to Files using Gsub

def gsub_file(relative_destination, regexp, *args, &block)
  path = destination_path(relative_destination)
  content = File.read(path).gsub(regexp, *args, &block)
  File.open(path, 'wb') { |file| file.write(content) }
end
@thisivan
thisivan / rails_database_reset.rb
Created December 9, 2009 00:19
Reset database on Rails
# Don't you ever use this on production environment
rake db:migrate:reset db:seed db:test:clone --trace
@thisivan
thisivan / couchdb_snippets.rdoc
Created December 2, 2009 18:42
CouchDB Snippets

CouchDB Snippets

Delete all your CouchDB databases:

rm -Rf /usr/local/var/lib/couchdb/*

URL to browse CouchDB databases: 127.0.0.1:5984/_utils

@thisivan
thisivan / homebrew-install.rb
Created October 28, 2009 12:37
HomeBrew Installation Script
#!/usr/bin/env ruby
require 'fileutils'
def fail!(msg = "Failure!")
puts(msg)
exit(1)
end
REPOSITORY_URL = 'git://github.com/mexpolk/homebrew.git'
PACKAGE_URL = 'http://github.com/mexpolk/homebrew/tarball/master'
# Rebase
$ git commit -a -m "Commit message"
$ git fetch
$ git rebase [branch] # origin/master
$ git push
# Stash
$ git stash
$ git pull
$ git stash apply
@thisivan
thisivan / random_chars.rb
Created June 23, 2009 17:40
Generate random strings in Ruby
# Random chars
chars = ('a'..'z').to_a + ('A'..'Z').to_a
(0...10).collect { chars[Kernel.rand(chars.length)] }.join
=> "nmhhuMrybz"
@thisivan
thisivan / benchmarks.rb
Created June 23, 2009 17:35
Sample benchmarks on Ruby
require 'benchmark'
puts Benchmark.measure { "a"*1_000_000 }
0.060000 0.000000 0.060000 ( 0.067556)
=> nil
n = 50000
Benchmark.bm do |x|
x.report { for i in 1..n; a = "1"; end }
x.report { n.times do ; a = "1"; end }
@thisivan
thisivan / mixin.rb
Created June 10, 2009 06:19
Sample Mixin
# = Mixin Template
# == Usage
# ActionController::Base.send :include, MixinModuleName
module MixinModuleName
def self.included(recipient)
recipient.extend(ClassMethods)
recipient.class_eval do
include InstanceMethods