Skip to content

Instantly share code, notes, and snippets.

@softwaregravy
softwaregravy / custom_job.rb
Created July 31, 2011 22:41
Pump custom values into hotoad
class CustomJob
def before(job)
Delayed::Context.set(:handler, job.handler)
Delayed::Context.set(:attempt, job.attempts + 1)
Delayed::Context.set(:last_error, job.last_error) if job.last_error
end
def after(job)
Delayed::Context.clear
@softwaregravy
softwaregravy / gist:1128135
Created August 5, 2011 18:06
Add an index
add_index :table, :column, :unique => true
remove_index :table, :column
@softwaregravy
softwaregravy / Gemfile.rb
Created August 5, 2011 18:36
Need a UUID
require 'uuidtools'
<%= form_tag(search_path, :method => "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
# from http://guides.rubyonrails.org/form_helpers.html
@softwaregravy
softwaregravy / registartion.rb
Created August 7, 2011 03:25
State machine driving registrations
state_machine do
state :email, :exit => lambda {|reg| reg.errors.clear }
state :age, :exit => lambda {|reg| reg.errors.clear }
state :complete, :enter => :register_user
event :next do
transitions :from => :email, :to => :age, :guard => :guard_to_age
transitions :from => :age, :to => :complete, :guard => :guard_to_complete
# do not allow complete => complete
end
@softwaregravy
softwaregravy / registrations_controller.rb
Created August 7, 2011 03:26
Using a state machine will give you a messy update
def update
@registration = Registration.find(params[:id])
redirect_to users_path(@registration.user_id) and return if @registration.state == 'complete'
if @registration.update_attributes(params[:registration])
if @registration.next!
if @registration.state == 'complete'
#can only reach this block on first completion -- or next will have failed
sign_in(:user, @registration.user)
redirect_to user_show_path and return
@softwaregravy
softwaregravy / registration.rb
Created August 7, 2011 03:28
Registar the User Implicitly
def register_user
password = User.send(:generate_token, 'encrypted_password').slice(0, 6)
user = User.create!(:name => name, :email => email, :age => age,
:password => password, :password_confirmation => password)
Notifications.signup(user, password).deliver
self.user = user
self.save!
end
@softwaregravy
softwaregravy / registration.rb
Created August 7, 2011 03:32
Check User validations in the Registration
def require_email
errors.add(:email, "Email is required") unless email.present?
if email.present?
errors.add(:email, "Email is already taken") if email_in_use?(email)
end
errors.empty?
end
@softwaregravy
softwaregravy / routes.rb
Created August 7, 2011 21:03
Routing with all in the path
namespace :path1 do
resources :my_resource
end
@softwaregravy
softwaregravy / routes.rb
Created August 7, 2011 21:05
Routing for a subdomain
scope :path1, :as => 'path1' do
constraints(SubdomainConstraints) do
resources :my_resource
end
end