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

all cheats avaliable

for install: sudo gem install cheat
+ info: http://cheat.errtheblog.com/

cheat sheets

migrations without timestamp

set in your environment.rb

config.active_record.timestamped_migrations = false

[ffmpeg] batch screenshot generator from flv

path = "."
videos = Dir["#{path}/*.flv"]
videos.each do |f|
  puts "converting #{f}"
  newFile = f.gsub(".flv", ".jpg")
  system("ffmpeg -itsoffset -4 -i #{f} -vframes 1 -an -f mjpeg -s 320x240 #{newFile}")
end

gem guide

http://docs.rubygems.org/read/book/2

gem outdated # give list of gems which are outdate

gem list # list of all gems in the system with thier version number.if there was 2 version then it would give them in descending order

gem cleanup # clean the older version when there are 2 version available

gem dependency rails # list all the dependencies for a gem

gem install rails –no-rdoc # skips documentation

gem server # run in localhost:8808 rdoc documentation

gem query --remote --name-matches rails # find a gem

gem sources # list repositories

find a gem to install

gem query --remote --name-matches rails

ruby get request

require 'net/http'
require 'uri'

url = URI.parse('http://www.rubyonrails.org')
res = Net::HTTP.start(url.host, url.port) do |http|
  http.get('/index.html')
end
puts res.body

current_url

this helper returns a current url

  def current_url
    url_for :only_path => false, :overwrite_params=>{}  
  end

time format in ruby

http://www.ruby-doc.org/core/classes/Time.html#M000236

  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character

easy send email in ruby

require 'rubygems'
require 'pony'
Pony.mail(:to => 'you@example.com', :from => 'me@example.com', :subject => 'Hello')

reads an entire file as string

def get_file_as_string(filename)
  data = ''
  f = File.open(filename, "r") 
  f.each_line do |line|
    data += line
  end
  return data
end

test = get_file_as_string 'myfile.txt'
puts test

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

record count and current records using will_paginate

returns Displaying records 1 - 10 of 35. used in codestacker

# 1) model:


  def self.per_page
    10
  end

# 2) helper:


  def paginate_range(in_collection, in_tot_count)
    endnumber = in_collection.offset + in_collection.per_page > in_tot_count ? 
      in_tot_count : in_collection.offset + in_collection.per_page
    "Displaying records #{in_collection.offset + 1} - #{endnumber} of #{in_tot_count}"
  end

# 3) controller 


    @codes = Code.paginate :conditions => conditions, :page => params[:page]
    @codes_count = Code.count

# 4) view: 


<%= paginate_range @codes, @codes_count %>

array guide

source: http://blog.carlosgabaldon.com/calabro/blog/post/2008/04/08/Ruby_Arrays

# Creating a new array


array = Array.new
# or

array = []

# Adding array elements By position


array = []
array[0] = "first element"

# To the end


array << "last element"
# This adds "last element" to the end of the array or


array.push("last element")
# This adds "last element" to the end of the array


# To the beginning


array = ["first element", "second element"]
array.unshift("before first element")

# This adds "before first element" to the beginning of the array

# Retrieving array elements


# By position


array = ["first element", "second element", "third element"]
third_element = array[2]
# This returns the third element.

# By positions


# second_and_third_element = array[1, 2]

# This returns a new array that contains the second & third elements

# Removing array elements


# From the beginning


array = ["first element", "second element"]
first_element = array.shift
# This removes "first element" from the beginning of the array

# From the end


last_element = array.pop
# This removes "second element" or the last element from the end of the array


# Combining arrays


# To a new array

array = [1, 2, 3]
array.concat([4, 5, 6, 7]) # [1, 2, 3, 4, 5, 6, 7]

# or

new_array = array + [4, 5, 6]
# Using the "+" method returns a new array, but does not modify the original array


# Modifying the array


array.replace([4, 5, 6]) # [4, 5, 6]

# Pairing items


array = [1, 2, 3]
new_paired_array = array.zip([4, 5, 6]) # [[1,4],[2, 5],[3, 6]]

# This creates an array of arrays


# Flattening array of arrays


array = [1, 2, 3]
new_paired_array_flattened = array.zip([4, 5, 6]).flatten # [1, 4, 2, 5, 3, 6]


# This flattens the arrays of arrays into one Array.


# Collecting array elements


array = [1, 2, 3]
array.collect {|x| x * 2 } # [2, 4, 6]


# Invokes block once for each element of self. Creates a new array containing the values returned by the block.


# Iterating over arrays


[1, 2, 3, 4] .each {|x| puts x}
# 1

# 2

# 3

# 4

# Filtering arrays


[1, 2, 3, 4, 5, 6] .find {|x| puts x > 5}
# This returns the first element that matches the block criteria.


# Querying arrays


array.find_all {|item| criteria }
# This returns a new array containing all the elements of the array that match the block criteria.


array.size
# This returns the number of elements in the array.


array.empty?
# This returns true if the array is empty; false otherwise.


array.include?(item)
# This returns true if the array contains the item; false otherwise.


array.any? {|item| criteria }
# This returns true if any item in the array matches the block criteria; false otherwise.


array.all? {|item| criteria }
# This returns true if all items in the array match the block criteria; false otherwise

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 %>

ruby array sum sample

simple sample

# an array with numbers

orders = %w(10 11.5 1.5 24 100) 

# convert array to float (originally in string format)

orders.map!{ |order| order.to_f } 

total = orders.inject() {|result, element| result + element}

turning numbers into ordinals

def ordinal(rank) 
  result = case rank 
    when 4..20: h(rank) + "th" 
    else 
    result = case (rank.modulo(10)) 
      when 1: h(rank) + "st" 
      when 2: h(rank) + "nd" 
      when 3: h(rank) + "rd" 
      else h(rank) + "th" 
    end 
  end 
  result 
end

age calculation

# one method

def age
 ((Time.now - birthday)/(60*60*24)/365.2422).to_i
end

# second method

def birthday
    @birthday = Time.local( birth_year, birth_month, birth_day )
  end
  
  def age
    ((Time.now - birthday) / 1.year).to_i
  end 

string manipulation

# using 'insert'


myString = "Paris in Spring" 
myString.insert 8, " the"  # returns "Paris in the Spring"


# using 'gsub' for remove non-alphabetic characters from a string


myString = "Only a test!!!" 
myString.gsub(/[^a-zA-Z|\s]/,'') # returns "Only a test"


# using 'gsub' for search & replace


myString = "I love ASP"
myString.gsub('ASP','Ruby') # returns "I love Ruby"

Displaying Code 41 - 60 of 69 in total