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

current_url Delicious

this helper returns a current url

show/hide lines
   1    def current_url
   2      url_for :only_path => false, :overwrite_params=>{}  
   3    end
created by leozera — 15 November 2008 — get a short url — tags: helper ruby embed

time format in ruby Delicious

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

show/hide lines
   1    %a - The abbreviated weekday name (``Sun'')
   2    %A - The  full  weekday  name (``Sunday'')
   3    %b - The abbreviated month name (``Jan'')
   4    %B - The  full  month  name (``January'')
   5    %c - The preferred local date and time representation
   6    %d - Day of the month (01..31)
   7    %H - Hour of the day, 24-hour clock (00..23)
   8    %I - Hour of the day, 12-hour clock (01..12)
   9    %j - Day of the year (001..366)
  10    %m - Month of the year (01..12)
  11    %M - Minute of the hour (00..59)
  12    %p - Meridian indicator (``AM''  or  ``PM'')
  13    %S - Second of the minute (00..60)
  14    %U - Week  number  of the current year,
  15            starting with the first Sunday as the first
  16            day of the first week (00..53)
  17    %W - Week  number  of the current year,
  18            starting with the first Monday as the first
  19            day of the first week (00..53)
  20    %w - Day of the week (Sunday is 0, 0..6)
  21    %x - Preferred representation for the date alone, no time
  22    %X - Preferred representation for the time alone, no date
  23    %y - Year without a century (00..99)
  24    %Y - Year with century
  25    %Z - Time zone name
  26    %% - Literal ``%'' character
created by leozera — 13 November 2008 — get a short url — tags: ruby time embed

easy send email in ruby Delicious

+ info:
http://adam.blog.heroku.com/past/2008/11/2/pony_the_express_way_to_send_email_from_ruby/
http://github.com/adamwiggins/pony/

show/hide lines
   1  require 'rubygems'
   2  require 'pony'
   3  Pony.mail(:to => 'you@example.com', :from => 'me@example.com', :subject => 'Hello')
created by leozera — 08 November 2008 — get a short url — tags: email ruby embed

reads an entire file as string Delicious

show/hide lines
   1  def get_file_as_string(filename)
   2    data = ''
   3    f = File.open(filename, "r") 
   4    f.each_line do |line|
   5      data += line
   6    end
   7    return data
   8  end
   9  
  10  test = get_file_as_string 'myfile.txt'
  11  puts test
created by leozera — 01 November 2008 — get a short url — tags: ruby string 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

record count and current records using will_paginate Delicious

returns “Displaying records 1 – 10 of 35”. used in codestacker

show/hide lines
   1  # 1) model:
   2  
   3    def self.per_page
   4      10
   5    end
   6  
   7  # 2) helper:
   8  
   9    def paginate_range(in_collection, in_tot_count)
  10      endnumber = in_collection.offset + in_collection.per_page > in_tot_count ? 
  11        in_tot_count : in_collection.offset + in_collection.per_page
  12      "Displaying records #{in_collection.offset + 1} - #{endnumber} of #{in_tot_count}"
  13    end
  14  
  15  # 3) controller 
  16  
  17      @codes = Code.paginate :conditions => conditions, :page => params[:page]
  18      @codes_count = Code.count
  19  
  20  # 4) view: 
  21  
  22  <%= paginate_range @codes, @codes_count %>
created by leozera — 22 October 2008 — get a short url — tags: ruby will_paginate embed

array guide Delicious

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

show/hide lines
   1  # Creating a new array
   2  
   3  array = Array.new
   4  # or
   5  array = []
   6  
   7  # Adding array elements By position
   8  
   9  array = []
  10  array[0] = "first element"
  11  
  12  # To the end
  13  
  14  array << "last element"
  15  # This adds "last element" to the end of the array or
  16  
  17  array.push("last element")
  18  # This adds "last element" to the end of the array
  19  
  20  # To the beginning
  21  
  22  array = ["first element", "second element"]
  23  array.unshift("before first element")
  24  
  25  # This adds "before first element" to the beginning of the array
  26  # Retrieving array elements
  27  
  28  # By position
  29  
  30  array = ["first element", "second element", "third element"]
  31  third_element = array[2]
  32  # This returns the third element.
  33  # By positions
  34  
  35  # second_and_third_element = array[1, 2]
  36  # This returns a new array that contains the second & third elements
  37  # Removing array elements
  38  
  39  # From the beginning
  40  
  41  array = ["first element", "second element"]
  42  first_element = array.shift
  43  # This removes "first element" from the beginning of the array
  44  # From the end
  45  
  46  last_element = array.pop
  47  # This removes "second element" or the last element from the end of the array
  48  
  49  # Combining arrays
  50  
  51  # To a new array
  52  array = [1, 2, 3]
  53  array.concat([4, 5, 6, 7]) # [1, 2, 3, 4, 5, 6, 7]
  54  # or
  55  new_array = array + [4, 5, 6]
  56  # Using the "+" method returns a new array, but does not modify the original array
  57  
  58  # Modifying the array
  59  
  60  array.replace([4, 5, 6]) # [4, 5, 6]
  61  # Pairing items
  62  
  63  array = [1, 2, 3]
  64  new_paired_array = array.zip([4, 5, 6]) # [[1,4],[2, 5],[3, 6]]
  65  # This creates an array of arrays
  66  
  67  # Flattening array of arrays
  68  
  69  array = [1, 2, 3]
  70  new_paired_array_flattened = array.zip([4, 5, 6]).flatten # [1, 4, 2, 5, 3, 6]
  71  
  72  # This flattens the arrays of arrays into one Array.
  73  
  74  # Collecting array elements
  75  
  76  array = [1, 2, 3]
  77  array.collect {|x| x * 2 } # [2, 4, 6]
  78  
  79  # Invokes block once for each element of self. Creates a new array containing the values returned by the block.
  80  
  81  # Iterating over arrays
  82  
  83  [1, 2, 3, 4] .each {|x| puts x}
  84  # 1
  85  # 2
  86  # 3
  87  # 4
  88  # Filtering arrays
  89  
  90  [1, 2, 3, 4, 5, 6] .find {|x| puts x > 5}
  91  # This returns the first element that matches the block criteria.
  92  
  93  # Querying arrays
  94  
  95  array.find_all {|item| criteria }
  96  # This returns a new array containing all the elements of the array that match the block criteria.
  97  
  98  array.size
  99  # This returns the number of elements in the array.
 100  
 101  array.empty?
 102  # This returns true if the array is empty; false otherwise.
 103  
 104  array.include?(item)
 105  # This returns true if the array contains the item; false otherwise.
 106  
 107  array.any? {|item| criteria }
 108  # This returns true if any item in the array matches the block criteria; false otherwise.
 109  
 110  array.all? {|item| criteria }
 111  # This returns true if all items in the array match the block criteria; false otherwise
created by leozera — 22 October 2008 — get a short url — tags: array ruby 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
Displaying records 1 - 10 of 23