Skip to content

Instantly share code, notes, and snippets.

View spohlenz's full-sized avatar

Sam Pohlenz spohlenz

View GitHub Profile
@spohlenz
spohlenz / application.js
Created August 11, 2008 18:17
Integrate jQuery with Rails' forgery protection and respond_to
$.ajaxSetup({
data: { authenticity_token: AUTHENTICITY_TOKEN },
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "text/javascript")
}
});
class Page < ActiveRecord::Base
acts_as_tree
def self.tree
hash = find(:all).inject({}) { |hash, p| hash[p.id] = [p, []]; hash }
hash.inject([]) { |result, (key, value)|
if parent_id = value.first.parent_id
hash[parent_id].last << value
else
result << value
function slugify(str) {
return str.toLowerCase().
replace(/&/g, 'and').
replace(/[^a-z0-9']+/g, '-').
replace(/^-|-$/g, '');
}
@spohlenz
spohlenz / flash_error.rb
Created November 16, 2008 22:25
The wrong way to set a flash error
def create
@recipe = Recipe.new(params[:recipe])
if @recipe.save
flash[:notice] = 'Recipe was successfully created.'
redirect_to recipes_path
else
flash[:error] = 'The recipe failed to save.'
render :action => 'new'
end
@spohlenz
spohlenz / recipes_controller.rb
Created November 16, 2008 22:45
Old controller pattern
class RecipesController < ApplicationController
...
def new
@recipe = Recipe.new
end
def create
@recipe = Recipe.new(params[:recipe])
@spohlenz
spohlenz / recipes_controller.rb
Created November 16, 2008 22:46
New controller pattern
class RecipesController < ApplicationController
...
def new
@recipe = flash[:recipe] || Recipe.new
end
def create
@recipe = Recipe.new(params[:recipe])
<% disabled do %>
Everything within this block will not get executed or output.
<% raise 'Foobar' # Even Ruby code won't be run %>
<% end %>
def disabled
# no-op
end
module Rack
class GoogleAnalytics
TRACKING_CODE = <<-EOCODE
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("{{ID}}");
class Locale
def initialize(identifier)
@identifier = identifier.to_s
end
def to_mongo
@identifier
end
def self.from_mongo(mongo)