you are here: codestackercodes [RSS] → tag rails [RSS]

javascript_include_all

http://blog.obiefernandez.com/content/2008/06/railsconf-2008.html

  def javascript_include_all
    includes = ''
    Dir.new("#{RAILS_ROOT}/public/javascripts").each do |js|
      next if js == "." or js == '..' or !js[".js"]
      includes += javascript_include_tag(js) + "\n"
    end
  end

bash script to create rails and subversion structure

#!/bin/bash

echo "########################################"
echo ""
echo ""
echo "This bash script creates a new rails project and do the initial svn import with ignoring/deleting files from subversion"
echo ""
echo ""
echo "#######################################"

echo "Enter svn username: "
read username
echo "Enter the svn url: "
read svn_url

echo "Enter Rails Application Path:(eg: /home/leonardofaria/Sites/): "
read app_path
echo "Enter Application Name: "
read app_name

echo "######################################"
echo "Please verify the following variables: "
echo "Svn Username: ${username}"
echo "Svn URL: ${svn_url}"
echo "Application Path: ${app_path}"
echo "Application name: ${app_name}"

echo "Proceed (y/n)"
read proceed

if [ ${proceed} = n ] || [ ${proceed} = N ]
    then
    echo "Terminating..."
    exit 0
elif [ ${proceed} = y ] || [ ${proceed} = Y ]
    then
    app_root="${app_path}/${app_name}"
    echo "Generating rails project: (${app_root})"
    rails ${app_root}

    echo "SVNinitial import: "
    svn import ${app_root} ${svn_url} -m "Initial Import" --username $username

    rm -rf ${app_root}
   
    echo "Checking out from svn: "

    svn checkout ${svn_url} ${app_root}
    cd ${app_root}
    echo "Removing all log files from SVN"
    svn remove log/*
    echo "commiting..."
    svn commit -m 'removing all log files from subversion'
    echo "Ignoring all log files under log dir"
    svn propset svn:ignore "*.log" log/
    echo "Updating and commiting..."
    svn update log/
    svn commit -m 'Ignoring all files in /log/ ending in .log'

    echo "Ignoring cache, sessions, sockets inside tmp dir"
    svn propset svn:ignore "*" tmp/sessions tmp/cache tmp/sockets
    echo "commiting tmp "
    svn commit -m "Ignoring all files in /tmp/"
    echo "Updating and commiting again...."

    svn update tmp/
    svn commit -m 'Ignore the whole tmp/ directory, might not work on subdirectories?'
    echo "Moving database.yml to database.example"
    svn move config/database.yml config/database.example
    echo "commiting..."
    svn commit -m 'Moving database.yml to database.example to provide a template for anyone who checks out the code'
    echo "Ignoring database.yml , updating and commiting..."
    svn propset svn:ignore "database.yml" config/
    svn update config/
    svn commit -m 'Ignoring database.yml'
    echo "Finished."

else
    echo "Unknown Input. Terminating..."
	exit 0
fi

render_component

it's only a remember.

render_component(:action => 'upload', :layout => 'popup', :params => { :l => params[:language], :d => params[:media][:definition_id], :t => 1 })

TODO rake task

this task show all TODO comments in your project.

save in lib/tasks/todo.rake

require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")
 
namespace :todo do
  desc 'List TODOs in all .rb files under app/'
  task(:list) do
      FileList["app/**/*.rb"].egrep(/TODO/)
  end
end

task for database backup

another solutions:

http://blog.craigambrose.com/articles/2007/03/01/a-rake-task-for-database-backups
http://tiago.zusee.com/blog/2007/06/12/rake-task-para-backup-de-banco-de-dados-em-rails/
http://derenci.us/2007/7/backup-do-banco-com-rake

require 'ftools'
require 'find'
namespace :db do
  desc "Backup the database to a file. Options: DIR=base_dir RAILS_ENV=production COMPACT=true MAX=2"
  task :backup => [:environment] do
    datestamp = Time.now.strftime("%Y-%m-%d")
    hourstamp = Time.now.strftime("%H-%M-%S")
    base_path = ENV["DIR"] || "db"
    backup_base = File.join(base_path, 'backup')
    backup_file = File.join(backup_base, "#{RAILS_ENV}_#{datestamp}_#{hourstamp}_dump.sql")
    File.makedirs(backup_base)
    db_config = ActiveRecord::Base.configurations[RAILS_ENV]
    host = " -h #{db_config['host']} " if db_config['host'] and !db_config['socket']

    sh "mysqldump #{host} -u #{db_config['username']} -p#{db_config['password']} #{db_config['database']} > #{backup_file}"
    puts "Created backup: #{backup_file}"
    
    sh "bzip2 -z #{backup_file}" if ENV["COMPACT"] == "true" 
    puts "Compacted backup: #{backup_file}.bz2" if ENV["COMPACT"] == "true" 
    
    dir = Dir.new(backup_base)
    all_backups = dir.entries[2..-1].sort
    max_backups = ENV["MAX"].to_i || 5
    unwanted_backups = all_backups[max_backups..-2] || []
    for unwanted_backup in unwanted_backups
      FileUtils.rm_rf(File.join(backup_base, unwanted_backup))
      puts "- Deleted old backup: #{unwanted_backup}" 
    end
    puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available"
  end
end

customize error messages

when a form is invalid, rails shows a default error message. for hide the messages, try these options:

<%= error_messages_for :order, :header_message => nil, :message => nil %>

new flash helper with prototype effects

create an application helper to manage your rails messages
concept by nando vieira [simplesideias.com.br]

  # paste application_helper.rb

  def flash_message 
    messages = ""
    [:notice, :info, :warning, :error].each {|type|
      if flash[type]
        messages += "<p class=\"#{type}\" id=\"alert\">#{flash[type]}</p>"
      end
    }    
    messages
  end

  ####################################


  # your layout 

  <%= flash_message %>
	
  <% content_tag :script, :type => "text/javascript" do %>
    $('alert').style.display = 'none';
    new Effect.Appear('alert', {duration: 3});
    setTimeout("new Effect.Fade('alert');", 10000);
  <% end %>

Phone.rb

Class form my CRM

class Phone
  attr_reader :country_code, :area_code, :number
  
  def initialize(country_code, area_code, number)
    @country_code, @area_code, @number = country_code, area_code, number
  end
  
  def ==(value)
    @country_code == value.country_code &&
    @area_code == value.area_code &&
    @number == value.number
  end
  
  def to_s
    @number ? "+#{@country_code} #{@area_code} #{@number}" : "n/a"
  end
end

validation sample

validates_format_of :company_url, :with => /((http|https):\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?)/ # valida URL

validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :on => :create, :message=>"has an invalid format" 
validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => 'email must be valid'
validates_format_of :login, :with => /\w+@\w+\.\w{2}/

Displaying Code 41 - 49 of 49 in total