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

Jesse Newland http://jnewland.com

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

open_body_tag

  #creates a body tag uniquely indentifying this page
  #takes an options Hash with two keys:
  #
  #<tt>id</tt>::        string that will be used as the body's ID. defaults to <tt>controller.controller_name.singularize</tt>
  #<tt>classes</tt>::   an Array of class names. defaults to <tt>[params[:action]]</tt>
  #
  #Examples:
  #
  # in HomeController#index:
  #
  # <%= open_body_tag %>
  # => <body id='home' class='index'>
  #
  # <%= open_body_tag(:id => 'foo') %>
  # => <body id='foo' class='index'>
  #
  # <%= open_body_tag(:id => 'foo', :classes => %w(one two)) %>
  # => <body id='foo' class='one two'>
  def open_body_tag(options = { :id => controller.controller_name.singularize, :classes => [params[:action]] })
    "<body id='#{options[:id]}' class='#{options[:classes].join(' ')}'>"
  end

Rails URL Validation

No regexes, allows URLs with ports or IPs. Inspiration from here

  validates_each :href, :on => :create do |record, attr, value|
    begin
      uri = URI.parse(value)
      if uri.class != URI::HTTP
        record.errors.add(attr, 'Only HTTP protocol addresses can be used')
      end
    rescue URI::InvalidURIError
      record.errors.add(attr, 'The format of the url is not valid.')
    end
  end

Synchronizing Rails DB Contents via Fixtures

The following rake task will dump the contents of the current environment's database to YAML fixtures. Stick the following in lib/tasks/fixtures.rake:

namespace :db do
  namespace :fixtures do
    
    desc 'Create YAML test fixtures from data in an existing database.  
    Defaults to development database.  Set RAILS_ENV to override.'
    task :dump => :environment do
      sql  = "SELECT * FROM %s"
      skip_tables = ["schema_info"]
      ActiveRecord::Base.establish_connection(:development)
      (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
        i = "000"
        File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
          data = ActiveRecord::Base.connection.select_all(sql % table_name)
          file.write data.inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
          }.to_yaml
        end
      end
    end
  end
end


After making changes to the database that you'd like to dump to fixtures:

rake db:fixtures:dump


After checking out updated fixtures from SVN:

rake db:migrate
rake db:fixtures:load

Capistrano : apply local patches when deploying from an external source code repository

I've submitted patches to a couple rails apps, and want to run off of their SCM's trunk code, but with my local patches applied. These Capistrano tasks will take any files matching
patches/*.diff
in your local directory, and apply them before restarting your app.

task :after_setup do
  patches_setup
end

task :after_update_code do
  send_and_apply_patches
end

task :patches_setup do
  run "mkdir -p #{deploy_to}/#{shared_dir}/patches" 
end

task :send_and_apply_patches do
  Dir[File.join(File.dirname(__FILE__), '../patches/*.diff')].sort.each do |patch|
    puts "sending #{File.basename(patch)}"
    put(File.read(patch),
       "#{deploy_to}/#{shared_dir}/patches/#{File.basename(patch)}",
       :mode => 0777)
    puts "applying #{File.basename(patch)}"
    run "cd #{release_path}; patch -p0 < #{deploy_to}/#{shared_dir}/patches/#{File.basename(patch)}"
  end
end

redirect or render

Quick method to help your XHR requests degrade gracefully - via the caboo.se

def redirect_or_render( redirect_to_hash, render_page  )  
  if @request.xhr?
    render(render_page)
  else
    redirect_to(redirect_to_hash)
  end
end


Use like this:

redirect_or_render(  
  {:action=>'foo'},
  { :partial => 'monkey', :locals => { :obj = > 'x' } }
)
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS