Never been to CodeSnippets 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!)

Failed generation of resource route for action

// description of your code here

These methods test that the routes for resources defined in routes.rb are working as expected. Call them from your functional (controller) tests.

Add the following 3 methods to test/test_helper.rb (updated for Rails 1.2.5 which no longer uses semicolons as a separator for the edit action):

# Test for routes generated by map.resource (singular).
def assert_routing_for_resource(controller, skip=[], nesting=[])
  routes = [
    ["new",'/new',{},:get], ["create",'',{},:post],
    ["show",'',{},:get], ["edit",'/edit',{},:get],
    ["update",'',{},:put], ["destroy",'',{},:delete]
    ]
  check_resource_routing(controller, routes, skip, nesting)
end
# Test for routes generated by map.resources (plural).
def assert_routing_for_resources(controller, skip=[], nesting=[])
  routes = [
    ["index",'',{},:get], ["new",'/new',{},:get], ["create",'',{},:post],
    ["show",'/1',{:id=>'1'},:get], ["edit",'/1/edit',{:id=>'1'},:get],
    ["update",'/1',{:id=>'1'},:put], ["destroy",'/1',{:id=>'1'},:delete]
    ]
  check_resource_routing(controller, routes, skip, nesting)
end

# Check that the expected paths will be generated by a resource, and that
# the expected params will be generated by paths defined by a resource.
# routes is array of [action, url string after controller, extra params].
def check_resource_routing(controller, routes, skip=[], nesting=[])
  # set a prefix for nested resources
  prefix = nesting.join('s/1/')
  unless prefix.blank?
    prefix += "s/1/"
  end
  # Add params for nested resources.
  # For each 'nest', include a ":nest_id=>'1'" param.
  params = {}
  nesting.each do |param|
    params["#{param}_id".to_sym] = '1'
  end
  # Test each of the standard resource routes.
  routes.each do |pair|
    unless skip.include? pair[0]
      assert_generates("/#{prefix}#{controller}#{pair[1]}",
        {:controller=>controller,
        :action=>pair[0]}.merge(pair[2]).merge(params), {}, {},
        "Failed generation of resource route for action #{pair[0]} /#{prefix}#{controller}#{pair[1]}")
      assert_recognizes(
        {:controller=>controller,
          :action=>pair[0]}.merge(pair[2]).merge(params),
        {:path=>"/#{prefix}#{controller}#{pair[1]}", :method=>pair[3]},
        {}, "Failed to recognize resource route for path #{pair[3]}:/#{prefix}#{controller}#{pair[1]}")
    end
  end
end





Altın Fiyatları
Revizyon ile Organize Matbaacılık Brnckvvtmllttrhaberi





My capistrano recipe for deploying on shared accelerator from a git repo

// deploy.rb - note that the git repo is also hosted on the shared accelerator

before("deploy:restart") { set :use_sudo, false } 
after "deploy:start", :restart_web_server
set :user, "my_user_name"
set :application, "myapp.com"
set :domain, "myapp.com"
set :joyent_primary_domain, "prospect.joyent.us"
set :repository, "ssh://my_user_name@prospect.joyent.us/users/home/my_user_name/git/myapp.git"
set :scm, :git
set :deploy_to, "/users/home/#{user}/domains/#{domain}/web"

set :use_sudo, false
role :app, "#{joyent_primary_domain}"
role :web, "#{joyent_primary_domain}"
role :db,  "#{joyent_primary_domain}", :primary => true

default_run_options[:pty] = true
namespace :deploy do
  desc "Restart Mongrel by killing" 
  task :restart, :roles => :app do
    run "pkill mongrel"
  end
end

Deployment Recipe for Joyent Shared Accelerator

This is the deploy.rb I am using with a Shared Accelerator (with a few changes). It assumes you are using Mongrel and a proxy to serve the application. Joyent has good examples for those in the KB.

Not everything is *required* for a Shared Accelerator, but better to have some placeholders if you move your application later. The standard Capistrano :setup task worked for me, surprisingly. Haven't tried it since 2.0 or so.

The tasks for deploy:web:disable and deploy:web:enable are hacks. Ideas would be appreciated. Using the "pkill mongrel" trick hasn't always worked for me (sometimes SMF doesn't restart it), so I do it manually.

This isn't perfect, but hopefully it helps.

### deploy.rb
  set :application, "my_application"
  set :domain, "humboldt.joyent.us"

  set :user, "my_user"
  set :runner, user
  set :admin_runner, user # Does nothing on a Shared Accelerator
  set :scm_username, user
  set(:scm_password){Capistrano::CLI.password_prompt("Subversion Password: ")}
  
  set :scm, :subversion
  set :repository, "svn+ssh://#{scm_username}@#{domain}/users/home/#{user}/svn/#{application}/trunk/"
  set :checkout, "export"

  role :app, domain
  # These aren't required if you are just using one Shared Accelerator, but it's good practice
  role :web, domain
  role :db, domain, :primary => true
  
  set :deploy_to, "/users/home/#{user}/web/#{application}" # Or wherever you want the application root to be

  set :service_name, "smf-service_name" # Irrelevant because SMF doesn't work from the CLI on shared - left in as a reminder of a dream
  set :mongrel_config, "#{deploy_to}/shared/config/mongrel_cluster.yml" # Similarly irrelevant on Shared
  set :use_sudo, false # Don't need sudo on a shared accelerator
  default_run_options[:pty] = true # Much time was lost figuring this one out - see http://weblog.jamisbuck.org/2007/10/14/capistrano-2-1

# Shared Accelerators don't allow CLI access to SMF on Solaris
# Capistrano will throw warnings/errors if you don't overwrite these methods.
# It's a good opportunity to throw in a reminder about it.
namespace :deploy do
  desc "Restart the service"
  task :restart, :roles => :app  do
    puts "Remember to restart this from Webmin for changes to take effect."
    # Some svcadm stuff would go here if it worked
  end
  
  desc "Start the service" # The :spinner task went out of style when Mongrel and the gang came to town
  task :start, :roles => :app  do
    puts "Remember to start this from Webmin for changes to take effect."
  end
  
  desc "Stop the service"
  task :stop, :roles => :app do
    puts "This service must be stopped from Webmin."
  end
  
  # These tasks are used to enable/disable the application by replacing a .htaccess file
  # Surely someone has a better idea.
  namespace :web do
    desc "Present a maintenance page to visitors."
    task :disable, :roles => :web do
      run "cp /users/home/#{user}/web/public/down.txt /users/home/#{user}/web/public/.htaccess"
    end
    
    desc "Makes the application web-accessible again."
    task :enable, :roles => :web do
      run "cp /users/home/#{user}/web/public/up.txt /users/home/#{user}/web/public/.htaccess"
    end
  end
end

Remove sudo password request when deploying

Change the sudoers list by adding a NOPASSWD: [Cmnd_Alias] line.

In terminal: visudo

# Cmnd alias specification
Cmnd_Alias HTTPD = /usr/local/sbin/apachectl, /etc/init.d/apache2

# User privilege specification
[user] ALL = NOPASSWD: HTTPD


Be sure that the NOPASSWD line is last in visudo, else, it risks being overwritten by later specifications.

sftp capistrano deployment strategy

// capistrano deployment strategy used when you have sftp access only (no ssh access)

require 'capistrano/recipes/deploy/strategy/base'
require 'fileutils'
require 'tempfile'  # Dir.tmpdir

require 'net/ssh'
require 'net/sftp'
require 'find'

module Capistrano
  module Deploy
    module Strategy

			# Special Strategy for a special price!
			# This strategy is created in favor of the sftp only apps, in lack of ssh login support
			# 
			# * exports the repository to a local directory
			# * uploads all the files to the remote server using an sftp script
			# * renames current directory to a directory with a timestamp of 1 hour ago
			# * renames the uploaded directory to current
      class SftpCopy < Base
        def deploy!
          logger.debug "getting (via #{copy_strategy}) revision #{revision} to #{destination}"
          system(command)
          File.open(File.join(destination, "REVISION"), "w") { |f| f.puts(revision) }

					logger.debug "Connecting to sftp user = #{configuration[:user]}"

					Net::SSH.start(configuration[:host], configuration[:user], configuration[:password]) do |ssh|
						ssh.sftp.connect do |sftp|
							logger.debug "Creating directory: #{remote_dir}"
							sftp.mkdir remote_dir, :permissions => 0755
							
							logger.debug "Uploading files from #{destination} to #{remote_dir}"
							logger.debug "Why don't you grab a cup of coffee while you wait, i might be busy for some time...\nJust sit back and enjoy the show..."
							Find.find(destination) do |file|
								if File.stat(file).directory?
									
									remote_directory = remote_dir + file.sub(destination, '')
									begin
										sftp.stat(remote_directory)
									rescue Net::SFTP::Operations::StatusException => e
										raise "BOEM" unless e.code == 2
										sftp.mkdir(remote_directory, :permissions => 0755)
									end
								else
									remote_file = remote_dir + file.sub(destination, '')
									sftp.put_file file, remote_file
									sftp.setstat(remote_file, :permissions => 0644)
								end
							end
							
							logger.debug "RENAMING DIRECTORIES"
							sftp.rename "#{configuration[:copy_remote_dir]}/current", "#{configuration[:copy_remote_dir]}/#{(Time.now - 1.hour).utc.strftime("%Y%m%d%H%M%S")}"
							sftp.rename "#{remote_dir}", "#{configuration[:copy_remote_dir]}/current"
						end
					end
        ensure
					logger.debug "Remove local export"
          FileUtils.rm_rf destination rescue nil
        end

        def check!
          super.check do |d|
          end
        end

        private

          # Returns the basename of the release_path, which will be used to
          # name the local copy and archive file.
          def destination
            @destination ||= File.join(tmpdir, File.basename(configuration[:release_path]))
          end

          # Returns the value of the :copy_strategy variable, defaulting to
          # :checkout if it has not been set.
          def copy_strategy
            @copy_strategy ||= configuration.fetch(:copy_strategy, :checkout)
          end

          # Should return the command(s) necessary to obtain the source code
          # locally.
          def command
            @command ||= case copy_strategy
            when :checkout
              source.checkout(revision, destination)
            when :export
              source.export(revision, destination)
            end
          end

          # Returns the name of the file that the source code will be
          # compressed to.
          def filename
            @filename ||= File.join(tmpdir, "#{File.basename(destination)}.#{compression_extension}")
          end

          # The directory to which the copy should be checked out
          def tmpdir
            @tmpdir ||= configuration[:copy_dir] || Dir.tmpdir
          end

          # The directory on the remote server to which the archive should be
          # copied
          def remote_dir
            @remote_dir ||= "#{configuration[:copy_remote_dir]}/#{File.basename(configuration[:release_path])}" || "/tmp"
          end
      end

    end
  end
end

Capistrano SFTP recipe

// webistrano recipe used to deploy with sftp access only

desc "Setup the rail environment"
namespace :deploy do
    task :setup do

    end

  task :default do
     update_code
     restart
  end

  task :update_code, :except => { :no_release => true } do
    on_rollback { run "rm -rf #{release_path}; true" }
    strategy.deploy!
  end

  task :symlink, :except => { :no_release => true } do

  end

  task :restart, :roles => :app do
     Net::SSH.start(host, user, password) do |ssh|
        ssh.sftp.connect do |sftp|
            sftp.remove("#{restart_file}")
        end
     end
  end
end


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

Variables for capistrano

Cap uses lots of symbols for pointing to variables.

When adjusting the value of a cap variable that is located in the standard.rb task library, you must use :set to adjust its value within your own recipe file (such as deploy.rb).

Example: :migrate_env is declared in Cap's standard.rb. To adjust its value, do not use a local variable named migrate_env to do so, it won't apply to the standard.rb library tasks.

set :migrate_geoip, "load_geoipcountry=false"
set :migrate_env, "#{migrate_geoip}"

Capistrano namespaces

when namespace is specified for a task, all subsequent tasks are assumed to be in the same namespace, reverting to non-namespaced task if not found

desc "OVERRIDE of deploy:cold"
deploy.task :cold, :roles => :app do
  puts "Overridden!"
  puts "Deploy method: #{deploy_via.to_s}"
  puts "Copy Strat: #{copy_strategy.to_s}"
  update
  migrate
  refresh_db
  mrs
end

Capistrano for TXD Containers

A mostly-standardized Capistrano deploy.rb file for the TXD containers. Adjust :application, :smf, :repository, :deploy_to as required; adjust the role definitions too if you want to use different hosts.

Copy your database.yml file to /home/example/rails/example.org/shared/config/database.yml and it'll get symlinked into place before the app is restarted.

This works with my SMF manifest here

set :application, "example.org"
set :smf, "mongrel/example"
set :repository, "https://example.textdriven.com/svn/#{application}"
set :deploy_to, "/home/example/rails/#{application}"
role :web, "#{application}", :primary => true
role :app, "#{application}", :primary => true
role :db, "#{application}", :primary => true

set :checkout, "export"
set :svn, "/opt/csw/bin/svn"
set :sudo, "/opt/csw/bin/sudo"
set :rake, "/opt/csw/bin/rake"

task :after_update_code do
  run "ln -s #{deploy_to}/#{shared_dir}/config/database.yml #{current_release}/config/database.yml"
  run "rm -f #{current_path}"
end

task :spinner, :roles => :app do
  send(run_method, "/usr/sbin/svcadm start #{smf}")
end

task :restart, :roles => :app do
  send(run_method, "/usr/sbin/svcadm restart #{smf}")
end