Ruby的25个编程细节(技巧、实用代码段)
1.try 永远不会抛出异常 在 没有的时候 返回 nil
province_id = province.find_by_name(prov).try(:id)
2.find(:first, :condotions) 方法 不言而与
mobile_info = mobileinfo.find(:first, :conditions => ["mobile_num = ? ", mobile_num.to_i])
3.find(:all, :select, :conditions)
support_amount_a = provincemerchantchangevalue.find(:all, :select => "distinct change_value_id",
:conditions => ["status = 1 and merchant_id = ? and province_id =? and channel_id in (select id from channels where status = 1)",
merchant_id, province_id]).map { |cv| cv.change_value_id }.compact
support_amount_s = changevalue.find(:all,:select => "price" ,:conditions => ["id in (?)", support_amount_a]) \
.map { |cv| cv.try(:price).to_i }.compact
4.发送post请求 可以在shell中执行
curl -d "channel=中信异度支付&action_type=娱人节-手机充值&user_indicate=13911731997&original_amount=10000" http://xx.xxx.xxx:3000/search.json
5.ruby 中纯数据结构 ( struct 与 openstruct )
讲一下它俩之间的区别:
struct 需要开头明确声明字段; 而 openstruct 人如其名, 随时可以添加属性
struct 性能优秀; 而 openstruct 差点, 具体的性能差距可看这里:http://*.com/questions/1177594/ruby-struct-vs-openstruct
struct 是 ruby 解释器内置, 用 c 实现; openstruct 是 ruby 标准库, ruby 实现
api 不同: struct api 与 openstruct
6. mime::type.register
mime::type.register "application/json", :ejson
config/initializers/mime_types.rb
7.config/initializers/secure_problem_solved.rb
activesupport::coreextensions::hash::conversions::xml_parsing.delete('symbol')
activesupport::coreextensions::hash::conversions::xml_parsing.delete('yaml')
8.config/initializers/new_rails_default.rb
if defined?(activerecord)
# include active record class name as root for json serialized output.
activerecord::base.include_root_in_json = true
# store the full class name (including module namespace) in sti type column.
activerecord::base.store_full_sti_class = true
end
actioncontroller::routing.generate_best_match = false
# use iso 8601 format for json serialized times and dates.
activesupport.use_standard_json_time_format = true
# don't escape html entities in json, leave that for the #json_escape helper.
# if you're including raw json in an html page.
activesupport.escape_html_entities_in_json = false
9.memcachestore 缓存
@_cache = activesupport::cache::memcachestore.new(
config['host'], { :namespace => "#{config['namespace']}::#{@name}" }
)
localhost::callback_lock
@_cache.write(pay_channel.channel_id,'true')
v = @_cache.read(pay_channel.channel_id)
if v.nil? || v != 'true'
return false
else
return true
end
end
10.联合索引
gem 'composite_primary_keys', '6.0.1'
https://github.com/momoplan
0.hash assert_valid_keys 白名单
11.puma -c puma_service_qa.rb
12.pow
13. time
start_time = start_time.to_s.to_datetime.at_beginning_of_day
end_time = end_time.to_s.to_datetime.end_of_day
14.merchant.instance_of? mplusmerchant
m_order[:merchant_id] = (merchant.instance_of? mplusmerchant) ? merchant.id : merchant
15.will_paginate rails
安装之后需要修改config/environment.rb文件
在文件的最后添加:
require 'will_paginate'
修改controller文件中的index方法:
# @products = product.find(:all)
@products = product.paginate :page => params[:page],
:per_page => 2
.pagination
= will_paginate @mplus_orders, :class => 'digg_pagination'
最好有个include
16. # excel generator
gem 'spreadsheet', '~> 0.7.3'
province = %w{ 安徽 北京 福建 甘肃 广东 广西 贵州 海南 河北 河南 黑龙江 湖北
湖南 吉林 江苏 江西 辽宁 内蒙古 宁夏 青海 山东 山西 陕西 上海
四川 天津 * * 云南 浙江 重庆 }
month = 1.upto(12).to_a
def self.total_to_xls(year = '2012', opts = {})
book = spreadsheet::workbook.new
sheet1 = book.create_worksheet
months = month
months = opts[:month].to_s.split(/,/) if opts[:month]
fixed_row = months.collect{ |m| m.to_s + '月' }.insert(0, '')
sheet1.row(0).concat(fixed_row)
row1 = ['']
(months.size - 1).times { row1 << ['用户数', '金额', '订单数'] }
sheet1.row(1).concat(row1.flatten!)
row = 2
sheet1.row(row).insert(0, '全国')
months.each_with_index do |m, i|
sheet1.row(row).insert(i*3 + 1, self.monthly_users_count(m))
sheet1.row(row).insert(i*3 + 2, self.monthly_amount(m))
sheet1.row(row).insert(i*3 + 3, self.monthly_orders_count(m))
end
province.each do |province|
row += 1
sheet1.row(row).insert(0, province)
months.each_with_index do |m, i|
sheet1.row(row).insert(i*3 + 1, self.monthly_users_count_by_province(m, province))
sheet1.row(row).insert(i*3 + 2, self.monthly_amount_by_province(m, province))
sheet1.row(row).insert(i*3 + 3, self.monthly_orders_count_by_province(m, province))
end
end
path = "tmp/phone_recharge.xls"
book.write path
path
end
17. inject({})
selected_conditions = base_conditions.inject({}) do |hash, data|
hash[data.first] = data.last unless data.last.blank?
hash
end
18.time_str.instance_of?
return time_str if time_str.instance_of? time
19.person.instance_eval
person.instance_eval do
def species
"homo sapien"
end
end
20.class_eval
class foo
end
metaclass = (class << foo; self; end)
metaclass.class_eval do
def species
"homo sapien"
end
end
end
21.ruby中 respond_to? 和 send 的用法
http://galeki.is-programmer.com/posts/183.html
因为obj对象没法响应talk这个消息,如果使用 respond_to? 这个方法,就可以实现判断对象能否响应给定的消息了
obj = object.new
if obj.respond_to?("talk")
obj.talk
else
puts "sorry, object can't talk!"
end
request = gets.chomp
if book.respond_to?(request)
puts book.send(request)
else
puts "input error"
end
22.method_missing,一个 ruby 程序员的梦中情人
def method_missing(method, *args)
if method.to_s =~ /(.*)_with_cent$/
attr_name = $1
if self.respond_to?(attr_name)
'%.2f' % (self.send(attr_name).to_f / 100.00)
else
super
end
end
end
23.chomp
chomp方法是移除字符串尾部的分离符,例如\n,\r等...而gets默认的分离符是\n
24. hash.each_pair{|k,v|} & send()
if bank_order.present?
data_hash.each_pair { |k, v| bank_order.send("#{k}=", v) }
else
bank_order = bankorder.new data_hash
end
25.config.middleware 通过 rake -t 可以查看, 在config/ - 去除不必的 middleware
26.1.day.ago.strftime('%y%m%d')