ruby rails3复制记录并创建新的

rails3复制记录并创建新的

rails2CopyRecordAndCreate.rb
// album.rb Model
class Album < ActiveRecord::Base
  def copy
    self.class.new.tap do |new_album| 
      attributes.each do |key, value|
        new_album.send("#{key}=", value) unless key == "id" 
      end
      new_album.save
    end 
  end
end

// albums_controller.rb
def copy
  original_album = Album.find(params[:id])
  @album = original_album.copy 
  redirect_to edit_album_path(@album),
    :notice => "This is a copy of #{original_album.title}"
end


// albums/show.html.erb
<%= button_to 'Copy', copy_album_path(@album) %> # http post by default
<% link_to "Copy", copy_album_path(@album), :method => :post %>  #http get by default

// routes.rb
resources :albums do
  member do 
    post :copy
  end 
end

ruby rails3 ajax切换属性

rails3 ajax切换属性

rails3AjaxToggleAttributes.rb
// Structure
rails g scaffold Article name:string approved:boolean

// routes
resources :articles do
  get 'toggle_approve', :on => :member
end

// Article Helper
def approve_link_text(approvable)
  approvable.approved? ? 'Un-approve' : 'Approve'
end

// Article View
<%= link_to approve_link_text(article), toggle_approve_article_path(article), 
  :remote => true %>
(OR)
<% @articles.each do |article| %>
  <%= article.name %>
  <%= link_to approve_link_text(@article), toggle_approve_article_path(@article), 
    :remote => true, 
    :id => "approve_link_#{@article.id}" %>
<% end %>    
  
  
// Article Controller
def toggle_approve  
  @a = Article.find(params[:id])  
  @a.toggle!(:approved)  
  render :nothing => true  
end

// toggle_approve.js.erb.
$("#approve_link_<%= @article.id %>")
  .text("<%= approve_link_text(@article) %>");

$("#article_<%= @article.id %>").effect("highlight");

ruby rails3自定义验证

rails3自定义验证

rails3CustomValidation.rb
validates_format_of :ssn,
  :with => /^[\d]{3}-[\d]{2}-[\d]{4}$/, 
  :message => "must be of format ###-##-####"
  
====================================================
// lib/custom_validations.rb

module CustomValidations
  def validates_ssn(*attr_names)
    attr_names.each do |attr_name| validates_format_of attr_name,
      :with => /^[\d]{3}-[\d]{2}-[\d]{4}$/,
      :message => "must be of format ###-##-####"
    end 
  end
end
ActiveRecord::Base.extend(CustomValidations)

// config/environment.rb
require 'custom_validations'

// model/student.rb

class Student < ActiveRecord::Base 
  validates_presence_of :name 
  validates_ssn :ssn
end

ruby LIB /任务/ resque.rake

LIB /任务/ resque.rake

resque.rake
require 'resque/tasks'

task "resque:setup" => :environment
task "resque:work"

namespace :resque do  
  task :setup => :environment
 
  desc "Restart running workers"
  task :restart_workers => :environment do
    Rake::Task['resque:stop_workers'].invoke
    Rake::Task['resque:start_workers'].invoke
  end
  
  desc "Quit running workers"
  task :stop_workers => :environment do
    stop_workers
  end
  
  desc "Start workers"
  task :start_workers => :environment do    
    run_worker("*", 1)
  end
  
  
  
  def store_pids(pids, mode)
    pids_to_store = pids
    pids_to_store += read_pids if mode == :append
 
    # Make sure the pid file is writable.    
    File.open(File.expand_path('tmp/pids/resque.pid', Rails.root), 'w') do |f|
      f <<  pids_to_store.join(',')
    end
  end
 
  def read_pids
    pid_file_path = File.expand_path('tmp/pids/resque.pid', Rails.root)
    return []  if ! File.exists?(pid_file_path)
    
    File.open(pid_file_path, 'r') do |f| 
      f.read 
    end.split(',').collect {|p| p.to_i }
  end
 
  def stop_workers
    pids = read_pids
    
    if pids.empty?
      puts "No workers to kill"
    else
      syscmd = "kill -s QUIT #{pids.join(' ')}"
      puts "$ #{syscmd}"
      `#{syscmd}`
      store_pids([], :write)
    end
  end
  
  # Start a worker with proper env vars and output redirection
  def run_worker(queue, count = 1)
    puts "Starting #{count} worker(s) with QUEUE: #{queue}"
 
    ##  make sure log/resque_err, log/resque_stdout are writable.
    ops = {:pgroup => true, :err => [(Rails.root + "log/resque_err").to_s, "a"], 
                            :out => [(Rails.root + "log/resque_stdout").to_s, "a"]}
    env_vars = {"QUEUE" => queue.to_s, 'RAILS_ENV' => Rails.env.to_s}
 
    pids = []
    count.times do
      ## Using Kernel.spawn and Process.detach because regular system() call would
      ## cause the processes to quit when capistrano finishes
      pid = spawn(env_vars, "rake resque:work", ops)
      Process.detach(pid)
      pids << pid
    end
    
    store_pids(pids, :append)
  end
end

ruby hh:mm:秒秒

hh:mm:秒秒

hours.rb
t = 270921
mm, ss = t.divmod(60)            #=> [4515, 21]
hh, mm = mm.divmod(60)           #=> [75, 15]
dd, hh = hh.divmod(24)           #=> [3, 3]
puts "%d days, %d hours, %d minutes and %d seconds" % [dd, hh, mm, ss]

ruby 在脚本中解析cli参数

在脚本中解析cli参数

parse_cli_arguments.rb
require 'optparse'
require 'optparse/date'

opts = OptionParser.new do |opts|
            opts.banner = "Usage: ruby karma_report_generator.rb [options]"

            opts.on('-p', '--projetctid ID', Integer, 'Project id') { |v| @options[:project_id] = v }
            opts.on('-s', '--startdate DATE', DateTime, 'Start date') { |v| @options[:start_date] = v }
            opts.on('-e', '--enddate DATE', DateTime, 'End date') { |v| @options[:end_date] = v }
            opts.on('-n', '--nameofspreadsheet NAME', 'Spreadsheet name') { |v| @options[:spreadsheet_name] = v }
          end

          opts.parse!

          if @options[:project_id].nil? || @options[:start_date].nil? || @options[:end_date].nil?
            puts opts
            raise OptionParser::MissingArgument
          end

ruby 加载YAML

加载YAML

load_yaml.rb
require 'yaml'
thing = YAML.load_file('some.yml')

ruby elasticsearch.rake

elasticsearch.rake
# Run with: rake environment elasticsearch:reindex
# Begins by creating the index using tire:import command
# This will create the "official" index name, e.g. "person" each time.
# Then we rename it to, e.g. "person20121001" and alias "person" to it.

namespace :elasticsearch do
  desc "re-index elasticsearch"
  task :reindex => :environment do

    klasses = [Ticket]

    klasses.each do |klass|
      puts "[Import] ::::::: Class: #{klass} :::::::::\n"

      ENV['CLASS'] = klass.name
      ENV['INDEX'] = new_index = klass.tire.index.name << '_' << Time.now.strftime('%Y%m%d%H%M%S')
      
      puts "[Import] New index name #{new_index}"

      Rake::Task["tire:import"].execute("CLASS='#{klass}'")

      puts '[IMPORT] about to swap index'
      if alias = Tire::Alias.find(klass.tire.index.name)
        puts "[IMPORT] aliases found: #{alias.indices.to_ary.join(',')}. deleting..."
        old_indices = alias.indices
        
        old_indices.each do |index|
          alias.indices.delete index
        end    
        
        alias.indices.add new_index
        alias.save
        
        old_indices.each do |index|          
          puts "[IMPORT] deleting index: #{index}"          
          i = Tire::Index.new(index)          
          i.delete if i.exists?
        end
      else
        puts "[IMPORT] no aliases found. deleting index. creating new one and setting up alias."
        klass.tire.index.delete
        alias = Tire::Alias.new
        alias.name(klass.tire.index.name)
        alais.index(new_index)
        alias.save
        puts "Saved alias #{klass.tire.index.name} pointing to #{new_index}"
      end

      puts "[IMPORT] done. Index: '#{new_index}' created."
    end
  end
end

ruby grep按混帐日志,TMs.rb

grep-git-logs-TMs.rb

Dir.chdir "/home/vagrant/app"
logs = `git log --pretty 1.2.0..1.2.1 | grep -E "(T ?M[-_ ]?[0-9]+|T ?T[-_ ]?[0-9]+)"`
labels = logs.each_line.map do |line|
  line.scan(/T ?[TM][-_ ]?[0-9]+/i).map do |s|
    s.upcase.gsub(/T ?([TM])[^\d]?(\d+)/, 'T\1-\2')
  end
end
final_list = labels.sort.uniq{|s|s.first}

final_list.each do |item|
  puts item.inspect
end

# # get last tag version
#
# git describe --abbrev=0 --tags
#
# # http://stackoverflow.com/questions/1404796/how-to-get-the-latest-tag-name-in-current-branch-in-git

ruby Capybara备忘单

Capybara备忘单

capybara cheat sheet.rb
# Navigating

  visit('/projects')
  visit(post_comments_path(post))

# Clicking links and buttons
  
  click_link('id-of-link')
  click_link('Link Text')
  click_button('Save')
  click('Link Text') # Click either a link or a button
  click('Button Value')

# Interacting with forms
  
  fill_in('First Name', :with => 'John')
  fill_in('Password', :with => 'Seekrit')
  fill_in('Description', :with => 'Really Long Text…')
  choose('A Radio Button')
  check('A Checkbox')
  uncheck('A Checkbox')
  attach_file('Image', '/path/to/image.jpg')
  select('Option', :from => 'Select Box')

# scoping

  within("//li[@id='employee']") do
    fill_in 'Name', :with => 'Jimmy'
  end

  within(:css, "li#employee") do
    fill_in 'Name', :with => 'Jimmy'
  end
  
  within_fieldset('Employee') do
    fill_in 'Name', :with => 'Jimmy'
  end
  
  within_table('Employee') do
    fill_in 'Name', :with => 'Jimmy'
  end

# Querying

  page.has_xpath?('//table/tr')
  page.has_css?('table tr.foo')
  page.has_content?('foo')
  page.should have_xpath('//table/tr')
  page.should have_css('table tr.foo')
  page.should have_content('foo')
  page.should have_no_content('foo')
  find_field('First Name').value
  find_link('Hello').visible?
  find_button('Send').click
  find('//table/tr').click
  locate("//*[@id='overlay'").find("//h1").click
  all('a').each { |a| a[:href] }

# Scripting
  
  result = page.evaluate_script('4 + 4');

# Debugging

  save_and_open_page

# Asynchronous JavaScript

  click_link('foo')
  click_link('bar')
  page.should have_content('baz')
  page.should_not have_xpath('//a')
  page.should have_no_xpath('//a')

# XPath and CSS

  within(:css, 'ul li') { ... }
  find(:css, 'ul li').text
  locate(:css, 'input#name').value
  Capybara.default_selector = :css
  within('ul li') { ... }
  find('ul li').text
  locate('input#name').value