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

javascript_include_all Delicious

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

show/hide lines
   1    def javascript_include_all
   2      includes = ''
   3      Dir.new("#{RAILS_ROOT}/public/javascripts").each do |js|
   4        next if js == "." or js == '..' or !js[".js"]
   5        includes += javascript_include_tag(js) + "\n"
   6      end
   7    end
created by leozera — 16 November 2008 — get a short url — tags: helper obie rails embed

bash script to create rails and subversion structure Delicious

show/hide lines
   1  #!/bin/bash
   2  
   3  echo "########################################"
   4  echo ""
   5  echo ""
   6  echo "This bash script creates a new rails project and do the initial svn import with ignoring/deleting files from subversion"
   7  echo ""
   8  echo ""
   9  echo "#######################################"
  10  
  11  echo "Enter svn username: "
  12  read username
  13  echo "Enter the svn url: "
  14  read svn_url
  15  
  16  echo "Enter Rails Application Path:(eg: /home/leonardofaria/Sites/): "
  17  read app_path
  18  echo "Enter Application Name: "
  19  read app_name
  20  
  21  echo "######################################"
  22  echo "Please verify the following variables: "
  23  echo "Svn Username: ${username}"
  24  echo "Svn URL: ${svn_url}"
  25  echo "Application Path: ${app_path}"
  26  echo "Application name: ${app_name}"
  27  
  28  echo "Proceed (y/n)"
  29  read proceed
  30  
  31  if [ ${proceed} = n ] || [ ${proceed} = N ]
  32      then
  33      echo "Terminating..."
  34      exit 0
  35  elif [ ${proceed} = y ] || [ ${proceed} = Y ]
  36      then
  37      app_root="${app_path}/${app_name}"
  38      echo "Generating rails project: (${app_root})"
  39      rails ${app_root}
  40  
  41      echo "SVNinitial import: "
  42      svn import ${app_root} ${svn_url} -m "Initial Import" --username $username
  43  
  44      rm -rf ${app_root}
  45     
  46      echo "Checking out from svn: "
  47  
  48      svn checkout ${svn_url} ${app_root}
  49      cd ${app_root}
  50      echo "Removing all log files from SVN"
  51      svn remove log/*
  52      echo "commiting..."
  53      svn commit -m 'removing all log files from subversion'
  54      echo "Ignoring all log files under log dir"
  55      svn propset svn:ignore "*.log" log/
  56      echo "Updating and commiting..."
  57      svn update log/
  58      svn commit -m 'Ignoring all files in /log/ ending in .log'
  59  
  60      echo "Ignoring cache, sessions, sockets inside tmp dir"
  61      svn propset svn:ignore "*" tmp/sessions tmp/cache tmp/sockets
  62      echo "commiting tmp "
  63      svn commit -m "Ignoring all files in /tmp/"
  64      echo "Updating and commiting again...."
  65  
  66      svn update tmp/
  67      svn commit -m 'Ignore the whole tmp/ directory, might not work on subdirectories?'
  68      echo "Moving database.yml to database.example"
  69      svn move config/database.yml config/database.example
  70      echo "commiting..."
  71      svn commit -m 'Moving database.yml to database.example to provide a template for anyone who checks out the code'
  72      echo "Ignoring database.yml , updating and commiting..."
  73      svn propset svn:ignore "database.yml" config/
  74      svn update config/
  75      svn commit -m 'Ignoring database.yml'
  76      echo "Finished."
  77  
  78  else
  79      echo "Unknown Input. Terminating..."
  80  	exit 0
  81  fi
created by leozera — 15 November 2008 — get a short url — tags: rails subversion embed

render_component Delicious

it’s only a remember.

show/hide lines
   1  render_component(:action => 'upload', :layout => 'popup', :params => { :l => params[:language], :d => params[:media][:definition_id], :t => 1 })
created by leozera — 29 October 2008 — get a short url — tags: rails ruby embed

TODO rake task Delicious

this task show all TODO comments in your project.

save in lib/tasks/todo.rake

show/hide lines
   1  require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")
   2   
   3  namespace :todo do
   4    desc 'List TODOs in all .rb files under app/'
   5    task(:list) do
   6        FileList["app/**/*.rb"].egrep(/TODO/)
   7    end
   8  end
created by leozera — 23 October 2008 — get a short url — tags: rails ruby embed

task for database backup Delicious

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

show/hide lines
   1  require 'ftools'
   2  require 'find'
   3  namespace :db do
   4    desc "Backup the database to a file. Options: DIR=base_dir RAILS_ENV=production COMPACT=true MAX=2"
   5    task :backup => [:environment] do
   6      datestamp = Time.now.strftime("%Y-%m-%d")
   7      hourstamp = Time.now.strftime("%H-%M-%S")
   8      base_path = ENV["DIR"] || "db"
   9      backup_base = File.join(base_path, 'backup')
  10      backup_file = File.join(backup_base, "#{RAILS_ENV}_#{datestamp}_#{hourstamp}_dump.sql")
  11      File.makedirs(backup_base)
  12      db_config = ActiveRecord::Base.configurations[RAILS_ENV]
  13      host = " -h #{db_config['host']} " if db_config['host'] and !db_config['socket']
  14  
  15      sh "mysqldump #{host} -u #{db_config['username']} -p#{db_config['password']} #{db_config['database']} > #{backup_file}"
  16      puts "Created backup: #{backup_file}"
  17      
  18      sh "bzip2 -z #{backup_file}" if ENV["COMPACT"] == "true" 
  19      puts "Compacted backup: #{backup_file}.bz2" if ENV["COMPACT"] == "true" 
  20      
  21      dir = Dir.new(backup_base)
  22      all_backups = dir.entries[2..-1].sort
  23      max_backups = ENV["MAX"].to_i || 5
  24      unwanted_backups = all_backups[max_backups..-2] || []
  25      for unwanted_backup in unwanted_backups
  26        FileUtils.rm_rf(File.join(backup_base, unwanted_backup))
  27        puts "- Deleted old backup: #{unwanted_backup}" 
  28      end
  29      puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available"
  30    end
  31  end
created by leozera — 23 October 2008 — get a short url — tags: rails rake ruby task embed

customize error messages Delicious

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

show/hide lines
   1  <%= error_messages_for :order, :header_message => nil, :message => nil %>
created by leozera — 17 October 2008 — get a short url — tags: error rails ruby embed

new flash helper with prototype effects Delicious

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

show/hide lines
   1    # paste application_helper.rb
   2    def flash_message 
   3      messages = ""
   4      [:notice, :info, :warning, :error].each {|type|
   5        if flash[type]
   6          messages += "<p class=\"#{type}\" id=\"alert\">#{flash[type]}</p>"
   7        end
   8      }    
   9      messages
  10    end
  11  
  12    ####################################
  13  
  14    # your layout 
  15    <%= flash_message %>
  16  	
  17    <% content_tag :script, :type => "text/javascript" do %>
  18      $('alert').style.display = 'none';
  19      new Effect.Appear('alert', {duration: 3});
  20      setTimeout("new Effect.Fade('alert');", 10000);
  21    <% end %>
created by leozera — 05 July 2008 — get a short url — tags: helper rails ruby script.aculo.us embed

Phone.rb Delicious

Class form my CRM

show/hide lines
   1  class Phone
   2    attr_reader :country_code, :area_code, :number
   3    
   4    def initialize(country_code, area_code, number)
   5      @country_code, @area_code, @number = country_code, area_code, number
   6    end
   7    
   8    def ==(value)
   9      @country_code == value.country_code &&
  10      @area_code == value.area_code &&
  11      @number == value.number
  12    end
  13    
  14    def to_s
  15      @number ? "+#{@country_code} #{@area_code} #{@number}" : "n/a"
  16    end
  17  end
created by fabioespindula — 04 July 2008 — get a short url — tags: rails ruby embed

validation sample Delicious

show/hide lines
   1  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
   2  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :on => :create, :message=>"has an invalid format" 
   3  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => 'email must be valid'
   4  validates_format_of :login, :with => /\w+@\w+\.\w{2}/
   5  
created by anonymous — 17 June 2008 — get a short url — tags: rails regex validation embed