Never been to TextSnippets 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 (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
125 total  XML / RSS feed 

Subversion Configuration Script for Your Rails Application

// Configure SVN for your rails app.

#!/bin/sh
svn remove log/*
svn commit -m"removing log files" 
svn propset svn:ignore "*.log" log/
svn update log/
svn commit -m 'Ignoring all files in /log/ ending in .log'
svn move config/database.yml config/database.example
svn commit -m 'Moving database.yml to database.example to provide a template for anyone who checks out the code'
svn propset svn:ignore "database.yml" config/
svn update config/
svn commit -m 'Ignoring database.yml'
svn remove tmp/*
svn propset svn:ignore "*" tmp/
svn update tmp/
svn commit -m "ignore tmp/ content from now" 
svn propset svn:ignore ".htaccess" config/
svn update config/
svn commit -m 'Ignoring .htaccess'
svn propset svn:ignore "dispatch.fcgi" config/
svn update config/
svn commit -m 'Ignoring dispatch.fcgi'

Install plugin on rails app

script/plugin install [name of plugin, or the url to the desired plugin]

Ubuntu 7.10: bootstrap a Ruby on Rails stack

// get started with ubuntu 7.1
// e.g. on a new slice from http://slicehost.com !

# 1) make yrself a user and stop being root

# 2) main web stack + ruby
sudo aptitude install -y make screen
sudo aptitude install -y apache2 php5 mysql-server
sudo aptitude install -y subversion postfix
sudo aptitude install -y ruby1.8 ruby1.8-dev rubygems irb
sudo aptitude install -y imagemagick librmagick-ruby1.8 librmagick-ruby-doc libfreetype6-dev xml-core

# 3) gemz
# rubygems appears to be broken as hell. 
# gem update --system does squat
# had to manually d/l rubygems 1.0.1, ruby setup.rb
wget http://rubyforge.org/frs/download.php/29548/rubygems-1.0.1.tgz
tar xzvf rubygems-1.0.1.tgz
cd rubygems-1.0.1
sudo ruby setup.rb
sudo gem install rails mongrel merb map_by_method


jQuery and Rails' respond_to

// Just throw this at the bottom of your application.js and you’re good to go: all jQuery ajax requests will trigger the wants.js block of your respond_to declaration, exactly like you’d expect. Enjoy.
// via: http://ozmm.org/posts/jquery_and_respond_to.html

jQuery.ajaxSetup({beforeSend’: function(xhr) {xhr.setRequestHeader(“Accept”,text/javascript”)} })

writing destructive string methods in Ruby

Use string class' method "replace" to overwrite its "self" value.

Example:

  def decapitalize!
    replace (self.reverse.chop + self.reverse.last.downcase).reverse
  end
  
  def decapitalize
    dup.decapitalize!
  end

Two or more parameters in RESTful route

Regardless of whether this is RESTful, to add multiple parameters to a normally RESTful route use the following

myresource_path(:id => myId, :extra_param => extraId, :extra_param2 => blah)


Results in
myresource/myId?extra_param=extraId&extra_param2=blah


See this Google Rails Group thread from Jeremy Kemper.

acts_as_state_machine model

// ActiveRecord plugin for managing state changes
// elitists.textdriven.com/svn/plugins/acts_as_state_machine/

class Something < ActiveRecord::Base

  # Validations
  validate :validate_state_change

  # State Machine States
  acts_as_state_machine :initial => :new
  state :new
  state :enabled,   :after => :after_enabled
  state :disabled,  :after => :after_disabled

  # State Machine Events
  event :enabled do
    transitions :from => :new,      :to => :enabled
    transitions :from => :disabled, :to => :enabled
  end
  
  event :disabled do
    transitions :from => :new,      :to => :disabled
    transitions :from => :enabled,  :to => :disabled
  end

  # Instance Methods
  def validate_state_change
    return if new_record?
    old = self.class.find(id)
    old_state = old.state
    new_state = self.state
    self.state = old_state
    if old_state != new_state
      begin
        if self.method("#{new_state}!").call != true
          errors.add(:state, "cannot transition from #{old_state} to #{new_state}")
        end
      rescue NameError
      end
      self.state = new_state
    end
  end
end

Restart Rails on Dreamhost

script/process/reaper --dispatcher=dispatch.fcg

Freezing Rails

rake rails:freeze:edge TAG=rel_1-2-6

SOAP4R Rails NameError FIX

// description of your code here

Update /Library/Ruby/Gems/1.8/gems/soap4r-1.5.8/lib/soap
  # KNOWN_TAG = XSD::NS::KNOWN_TAG.dup.update(
  #   SOAP::EnvelopeNamespace => 'env'
  # ) # Replaced with code from http://dev.ctor.org/soap4r/ticket/433
  KNOWN_TAG = {
      XSD::Namespace => 'xsd', XSD::InstanceNamespace => 'xsi', SOAP::EnvelopeNamespace => 'env'
  }

Freeze rails

Freeze rails 1.2.3 to a project through rubyonrails.org TRAC.

rake rails:freeze:edge TAG=rel_1-2-3

Static Pages in Rails without Corresponding Controllers

// See if a file exists on a path provided by a record in your database

def show
        page_url = params[:url].join('/')
        if File.exists?("#{RAILS_ROOT}/app/views/pages/#{page_url}")
                render :template => "static/#{page_url}"
        end
end

old deprecated legacy plugins repository for Rails

// description of your code here

Find old official rails trunk plugins that didn't make the cut here:

http://dev.rubyonrails.org/svn/rails/plugins/legacy/

rails console - add module methods

Extend the functionality of the rails console by mixing in modules

>> extend ERB::Util
=> #
>> h('blahblah')
=> "<b>blahblah</b>"


You can extend ActionView::Helpers, etc. with this to provide view method functionality in the console.

http://errtheblog.com/post/43

Capistrano task to load production data

# load production data, still needs some polish
# based on code from http://push.cx/2007/capistrano-task-to-load-production-data
# cap 2.0 compatible
# exec is being weird, had to end w/ a syscall :\ any ideas?

desc "Load production data into development database"
task :load_production_data, :roles => :db, :only => { :primary => true } do
  require 'yaml'
  ['config/database.yml'].each do |file|

    database = YAML::load_file(file)

    filename = "dump.#{Time.now.strftime '%Y-%m-%d_%H:%M:%S'}.sql.gz"
    # on_rollback { delete "/tmp/#{filename}" }

    # run "mysqldump -u #{database['production']['username']} --password=#{database['production']['password']} #{database['production']['database']} > /tmp/#{filename}" do |channel, stream, data|
    run "mysqldump -h #{database['production']['host']} -u #{database['production']['username']} --password=#{database['production']['password']} #{database['production']['database']} | gzip > /tmp/#{filename}" do |channel, stream, data|
      puts data
    end
    get "/tmp/#{filename}", filename
    # exec "/tmp/#{filename}"
    password = database['development']['password'].nil? ? '' : "--password=#{database['development']['password']}"  # FIXME pass shows up in process list, do not use in shared hosting!!! Use a .my.cnf instead
    # FIXME exec and run w/ localhost as host not working :\
    # exec "mysql -u #{database['development']['username']} #{password} #{database['development']['database']} < #{filename}; rm -f #{filename}"
    `gunzip -c #{filename} | mysql -u #{database['development']['username']} #{password} #{database['development']['database']} && rm -f gunzip #{filename}`
  end
  
end

Never render the full layout in a Rails view when called via AJAX

Essential for degradable javascript, when one never knows if a view or partial is being called via XmlHttpRequest or not. Throw the below code in your ApplicationController (application.rb)

More info in this blog post

def render(*args)
        args.first[:layout] = false if request.xhr? and args.first[:layout].nil?
        super
end

eliminate duplicate flash on before_filter methods

When using a before filter to prevent unauthorized access to methods, use flash.now instead of flash, when painting error messages.

flash.now[:warning] = "You must be the group admin (and logged in) to edit."


see KerryBuckley.com for more info

ruby_inline permission denied when starting mongrel_cluster from init.d

The cause is the project is trying to read /root/.ruby_inline/Inline_ImageScience_aa58.c, yet the user running the rails project is the one specified in the /config/mongrel_cluster.yml (usually some other user that is NOT root).

When the project references anything to do with ImageScience, it will complain that it has insufficient rights to read the c library file, of course, since it's in root's home dir.

Solution, specify a home environment variable in your rails project's production.rb file (/rails_project/config/environments/production.rb)

ENV['HOME'] = '/home/billy'


Now when the project is started from system boot, or manually by calling ./etc/init.d/mongrel_cluster start, the rails project will always look to the user's home directory, rather than root's.

EDIT:

Or better yet, use this patch to lib/mongrel/configurator.rb
(was posted at ruby-on-rails talk google groups)
-          log "Changing user to #{user}." 
-          Process::UID.change_privilege(Etc.getpwnam(user).uid)
+          log "Changing user to #{user}."
+          getpwnam = Etc.getpwnam(user)
+          Process::UID.change_privilege(getpwnam.uid)
+          ENV['HOME'] = getpwnam.dir

Rotate Rails Log files

// description of your code here
Keeps 50 files of a maximum size of 5MB each

config.logger = Logger.new("#{RAILS_ROOT}/log/#{ENV['RAILS_ENV']}.log", 50, 5242880)

field focus in rails template

Stick the following in application_helper.rb:

def set_focus_to_id(id)
  javascript_tag("$('#{id}').focus()");
end


Then this in the templates as needed to generate a javascript focus tag.
(Note this exaple pretends to set focus for a field with id='user_login').
<%= set_focus_to_id 'user_login' %>
« Newer Snippets
Older Snippets »
125 total  XML / RSS feed