1.require 'cgi'
def self.escape_request_params(args)
pairs = args.strip.split('&')
pairs.map do |pair_txt|
pair = pair_txt.split('=')
"#{pair[0]}=#{CGI.escape(pair[1])}" if pair[1]
end.join('&')
end
CGI.unescape
2.require 'logger'
require "rubygems"
require 'active_record'
log_file = "#{PWD}/../log/database.log"
ActiveRecord::Base.logger = Logger.new(log_file)
ActiveRecord::Base.logger.level = Logger::INFO
if local_machine?
begin
`> #{log_file}`
ActiveRecord::Base.logger.level = Logger::DEBUG
rescue;end
end
3.require 'find'
MODELS_DIR = "#{RAILS_ROOT}/app/models" unless defined?(MODELS_DIR)
Find.find(MODELS_DIR) do |path|
require path if path =~ /\.rb$/
end
4.require 'drb'
类似java的RMI
ServerURL = "druby://61.135.169.125:4000"
class Dispatch
def ask_adwords_us
end
end
dispatch = Dispatch.new
DRb.start_service ServerURL, dispatch
@dispatch_server = DRbObject.new nil, ServerURL
@dispatch_server.ask_adwords_us
5.require 'fileutils'
FileUtils.remove(path)
FileUtils.cp(from,to)
FileUtils.ln(source,path)
FileUtils.rm_f(path)
FileUtils.chmod(path)
FileUtils.mv(from,to)
FileUtils.mkdir_p(path)
FileUtils.touch(path)
6.
require "#{File.dirname(__FILE__)}/../config/initializers/ext"
Dir.glob("#{RAILS_ROOT}/app/models/*").select { |f| File.directory? f }
返回据绝对路径的arr
7.require 'yaml'
test_obj = ["dogs", "cats", "badgers"]
yaml_obj = YAML::dump(test_obj)
ruby_obj = YAML::load(yaml_obj) => ["dogs", "cats", "badgers"]
ruby_obj == test_obj => true
############config.yml##############################
refetch_count: 2
client_server_url: druby://localhost:8777
dispatch_server_url: druby://localhost:8666
adwords: 1
yahoo: 8
google: 12
bing: 15
############config.yml##############################
config_path = '/home/simon/文档/monitor_v3/config/config.yml'
config = YAML::load(File.open(config_path))
返回hash
Signal.trap("TERM")
8.require 'csv'
CSV::Reader.parse(File.open(csv_file_path, "r")) do |line|
c = Card.find_or_create_by_term_and_collection_id(line[0], collection_id)
c.update_attributes(:definition => line[1], :user_id => user_id)
end
9.
require 'md5'
MD5.hexdigest(`uuidgen`.strip!)
#目前不是很安全,碰撞算法能导致冲突
############################################
require 'digest/sha1'
Digest::SHA1.hexdigest(`uuidgen`.strip!)
#目前还比较安全
############################################
require 'openssl'
require 'base64'
KEY = "9706a6217733d43a5f3bf5e42663ba67"
def self.des_encrypt(message)
cipher = OpenSSL::Cipher::Cipher.new("des-cbc")
cipher.encrypt
cipher.key = KEY
text = cipher.update(message)
text << cipher.final
Base64.encode64(text)
end
def self.des_decrypt(message)
_message = Base64.decode64(message)
cipher = OpenSSL::Cipher::Cipher.new("des-cbc")
cipher.decrypt
cipher.key = KEY
text = cipher.update(_message)
text << cipher.final
end
############################################
10.
require 'open-uri'
require 'uri'
11.多线程
Thread synchronization: Mutex or Monitor?
Ruby Mutex is quite advanced, pure OO and even can be mixed into any
object (require "mutex_m.rb") exactly the same way as Ruby Monitor.
So, in terms of their functionality and usage they can do the same
things with the same API. Mutex #synchronize allows for control of
multiple access points the same way as Mutex #synchronize does.
require 'monitor'
monit = Monitor.new
require 'thread'
mutex = Mutex.new
require 'drb'
mutex = Mutex.new
12.
#params['file'] from the form
def upload_file(file)
if !file.original_filename.empty?
@filename = file.original_filename
File.open("#{RAILS_ROOT}/public/images/#{@filename}", "wb") do |f|
f.write(file.read)
end
return @filename
end
end
# params[:file] is Tempfile obj from the page
img = Magick::Image.from_blob(params[:file].read)[0]
img.write("#{filename}")
#r,w,rw,w+,rb,wb
13.
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/core_ext/rexml.rb
/usr/lib/ruby/1.8/rexml /rexml.rb
#require 'rubygems'
#require 'active_support' #重新包装了rexml
require 'rexml/rexml'
require 'rexml/document'
str = <<-EOF
<?xml version='1.0' encoding='UTF-8'?>
<students desc='Class3'>
<student info='not bad'><name>simon</name><birth>1986</birth><score>98</score></student>
<student info='very good'><name>tom</name><birth>1988</birth><score>79</score></student>
<student info='just-so-so'><name>edwa</name><birth>1987</birth><score>95</score></student>
</students>
EOF
REXML::Document.new(str).root.elements.each_with_index do |element, i|
#puts element.methods - "".methods
puts "<<<<<<<<<<#{i+1}<<<<<<<<<<<<<<<<<<"
puts element.attribute("info")
puts "------------------"
puts element.get_elements("name")
puts element.get_text("name").value
puts "------------------"
puts element.get_elements("birth")
puts element.get_text("birth").value
puts "------------------"
puts element.get_elements("score")
puts element.get_text("score").value
puts ">>>>>>>>>#{i+1}>>>>>>>>>>>>>>>>>>"
end
14.parse json
require 'rubygems'
require 'active_support'
1.8.7 :012 > j
=> "[{\"birth\":1986,\"name\":\"tom\",\"score\":90},{\"birth\":1988,\"name\":\"simon\",\"score\":99}]"
_j = ActiveSupport::JSON.decode(j)
=> [{"name"=>"tom", "birth"=>1986, "score"=>90}, {"name"=>"simon", "birth"=>1988, "score"=>99}]
15
require 'net/http'
require 'uri'
HTTP.post_form URI.parse('http://www.example.com/search.cgi'), { "q" => "ruby", "max" => "50" }
str = Net::HTTP.get(URI.parse('http://www.baidu.com'))
res = Net::HTTP.get_response(URI.parse('http://www.example.com/index.html'))
print res.body
16.require 'iconv'
def utf8_to_gbk
encode_convert(self, "GBK", "UTF-8")
end
def gbk_to_utf8
encode_convert(self, "UTF-8", "GBK")
end
def encode_convert(s, to, from)
converter = Iconv.new(to, from)
converter.iconv(s)
end
17
sudo gem install json_pure
require 'rubygems'
require 'json'
require 'pp'
json = File.read('abc.json')
h = JSON.parse(json)
18.
def abc
str = '{"ret":1,"start":"123.122.208.0","end":"123.123.31.255","country":"\u4e2d\u56fd","province":"\u5317\u4eac","city":"\u5317\u4eac","district":"","isp":"\u8054\u901a","type":"","desc":""}"
json = JSON.parse(str)
puts "#{
json
[:city]}" #北京
puts json [:city] # \345\214\227\344\272\254
return json
end