Skip to content

Instantly share code, notes, and snippets.

@withhawaii
withhawaii / UpdateUsers1.rb
Last active April 27, 2016 21:01
Sometime you may need to modify multiple table columns in a migration. Here is my best practice when you need to update multiple table columns in a migration.
#The example below will easily get screwed up when your statements fails in the middle of migrations, i.e., fail after the line 9.
#It will require manual fix to recover your table to healthy state.
#MySQL support does not support rollbacking DDL statements (Postgres does it though).
class UpdateUsers < ActiveRecord::Migration
def change
add_column(:users, :type, :string)
remove_column(:users, :first_name)
remove_column(:users, :last_name)
rename_column(:users, :dob, :birth_date)
@withhawaii
withhawaii / database.yml
Created February 12, 2016 09:30
Prompt MySQL root password only when you are running rake. This way, you can set minimum required MySQL privileges to 'app_user'.
<%
rake = File.split($0).last == 'rake'
if rake
begin
STDOUT.puts "MySQL root Password:"
password = STDIN.gets.strip.downcase
end until password.length > 0
end
%>
@withhawaii
withhawaii / person.rb
Last active August 29, 2015 14:15
Using Arel and Scope to implement SQL "LIKE" statements
class Person < ActiveRecord::Base
scope :matches, lambda {|conditions|
where conditions.map {|key, value|
if value.is_a? Array
value.map {|v| arel_table[key].matches("%#{v}%")}
else
arel_table[key].matches("%#{value}%")
end
}.flatten.inject(:or)
}
@withhawaii
withhawaii / paperclip.rb
Created September 19, 2014 20:13
Setting up Paperclip to upload files into OpenStack object storage
Paperclip::Attachment.default_options.update(
{
:path => ":class/:attachment/:hash/:style.:extension",
:storage => :fog,
:fog_credentials => {
:provider => 'OpenStack',
:openstack_username => 'user',
:openstack_api_key => 'password',
:openstack_auth_url => 'auth_url',
},