Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Deploying on a passenger / mod_rails host with capistrano

// add this to deploy.rb

namespace :mod_rails do
  desc <<-DESC
  Restart the application altering tmp/restart.txt for mod_rails.
  DESC
  task :restart, :roles => :app do
    run "touch  #{release_path}/tmp/restart.txt"
  end
end

namespace :deploy do
  %w(start restart).each { |name| task name, :roles => :app do mod_rails.restart end }
end

Initial caps with ruby on rails

class String
  # unicode_str.initial_caps => new_str
  # returns a copy of a string with initial capitals
  # "Jules-Édouard".initial_caps => "J.É."
  def initial_caps
    self.tr('-', ' ').split(' ').map { |word| word.chars.first.upcase.to_s + "." }.join
  end
end

Make your model play nice with SEO

## config/initializers/string_extensions.rb

require 'unicode'

class String
  def to_slug
    str = Unicode.normalize_KD(self).gsub(/[^\x00-\x7F]/n,'')
    str = str.gsub(/\W+/, '-').gsub(/^-+/,'').gsub(/-+$/,'').downcase
  end

  def numeric?
    if self =~ /^\d+$/
      self.to_i
    elsif self =~ /^\d+([,\.]\d+)?$/
      self.tr(',','.').to_f
    else
      false
    end
  end
end


## app/models/article.rb

# string :title
# text   :body
# string :permalink
class Article < ActiveRecord::Base
  before_save :set_permalink

  # article_path(@article)
  # >> /article/5
  # article_path(@article.permalink)
  # /article/pink-ferret
  def self.find(*args)
    if args.first.is_a?(String) and !args.first.numeric?
      find_by_permalink(args.shift,*args) or raise ActiveRecord::RecordNotFound
    else
      super
    end
  end

  # article_path(@article)
  # >> /article/5-pink-ferret
  def to_param
    "#{id}-#{permalink}"
  end

  private
  def set_permalink
    self.permalink = title.to_slug
  end
end

A SEO-compliant slug for your titles

# This instance method can handle any latin string

require 'unicode'

class String
  def to_slug
    str = Unicode.normalize_KD(self).gsub(/[^\x00-\x7F]/n,'')
    str = str.gsub(/\W+/, '-').gsub(/^-+/,'').gsub(/-+$/,'').downcase
  end
end
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS