Ruby 一些常用的细节

来源:互联网 发布:123 网络 编辑:程序博客网 时间:2024/06/05 22:49




1.try 永远不会抛出异常 在 没有的时候 返回 nil 

[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. province_id = Province.find_by_name(prov).try(:id)  


2.find(:first, :condotions) 方法 不言而与
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. mobile_info = MobileInfo.find(:first:conditions => ["mobile_num = ? ", mobile_num.to_i])  


3.find(:all, :select, :conditions)
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. support_amount_a = ProvinceMerchantChangeValue.find(:all:select => "DISTINCT change_value_id",  
  2.                         :conditions => ["status = 1 and merchant_id = ? and province_id =? and channel_id in (select id from channels where status = 1)",  
  3.                         merchant_id, province_id]).map { |cv| cv.change_value_id }.compact  
  4.   
  5. support_amount_s = ChangeValue.find(:all,:select => "price" ,:conditions => ["id in (?)", support_amount_a]) \  
  6.                                   .map { |cv| cv.try(:price).to_i }.compact  



4.发送post请求 可以在shell中执行  

[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. curl -d "channel=中信异度支付&action_type=娱人节-手机充值&user_indicate=13911731997&original_amount=10000" http://xx.xxx.xxx:3000/search.json  


 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://stackoverflow.com/questions/1177594/ruby-struct-vs-openstruct
Struct 是 Ruby 解释器内置, 用 C 实现; OpenStruct 是 Ruby 标准库, Ruby 实现
API 不同: Struct API 与 OpenStruct
6. MIme::Type.register

[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Mime::Type.register "application/json":ejson  



config/initializers/mime_types.rb


7.config/initializers/secure_problem_solved.rb
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. ActiveSupport::CoreExtensions::Hash::Conversions::XML_PARSING.delete('symbol')  
  2. ActiveSupport::CoreExtensions::Hash::Conversions::XML_PARSING.delete('yaml')   


8.config/initializers/new_rails_default.rb

[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. if defined?(ActiveRecord)  
  2.   # Include Active Record class name as root for JSON serialized output.  
  3.   ActiveRecord::Base.include_root_in_json = true  
  4.   
  5.   # Store the full class name (including module namespace) in STI type column.  
  6.   ActiveRecord::Base.store_full_sti_class = true  
  7. end  
  8.   
  9. ActionController::Routing.generate_best_match = false  
  10.   
  11. # Use ISO 8601 format for JSON serialized times and dates.  
  12. ActiveSupport.use_standard_json_time_format = true  
  13.   
  14. # Don't escape HTML entities in JSON, leave that for the #json_escape helper.  
  15. # if you're including raw json in an HTML page.  
  16. ActiveSupport.escape_html_entities_in_json = false  



9.MemCacheStore 缓存

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. @_cache = ActiveSupport::Cache::MemCacheStore.new(  
  2.                       CONFIG['host'], { :namespace => "#{CONFIG['namespace']}::#{@name}" }  
  3.                       )  
  4.   
  5. localhost::callback_lock  
  6.   
  7. @_cache.write(pay_channel.channel_id,'true’)  
  8. v = @_cache.read(pay_channel.channel_id)  
  9. if v.nil? || v != 'true'  
  10.       return false  
  11.     else  
  12.       return true  
  13.     end  
  14. end  



10.联合索引
gem 'composite_primary_keys', '6.0.1'

https://github.com/momoplan


10.Hash assert_valid_keys 白名单


11.puma -C puma_service_qa.rb

12.pow 

13. Time
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. start_time = start_time.to_s.to_datetime.at_beginning_of_day  
  2. end_time = end_time.to_s.to_datetime.end_of_day  


14.merchant.instance_of? MplusMerchant
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. m_order[:merchant_id] = (merchant.instance_of? MplusMerchant) ? merchant.id : merchant  

15.will_paginate rails
安装之后需要修改config/environment.rb文件 
在文件的最后添加: 
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. require 'will_paginate'   
  2. 修改controller文件中的index方法:   
  3. #    @products = Product.find(:all)   
  4.     @products = Product.paginate  :page => params[:page],   
  5.                                   :per_page => 2   
  6.   .pagination  
  7.     = will_paginate @mplus_orders:class => 'digg_pagination'  
  8.   
  9. 最好有个include  



16. # Excel Generator
gem 'spreadsheet', '~> 0.7.3'

 
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. PROVINCE = %w{ 安徽  北京  福建  甘肃  广东  广西  贵州  海南  河北  河南  黑龙江 湖北   
  2.      湖南  吉林  江苏  江西  辽宁  内蒙古 宁夏  青海  山东  山西  陕西  上海   
  3.      四川  天津  西藏   新疆  云南  浙江  重庆 }  
  4.   
  5.  MONTH = 1.upto(12).to_a  
  6.   
  7.  def self.total_to_xls(year = '2012', opts = {})  
  8.    book = Spreadsheet::Workbook.new  
  9.    sheet1 = book.create_worksheet  
  10.    months = MONTH  
  11.    months = opts[:month].to_s.split(/,/) if opts[:month]  
  12.   
  13.    fixed_row = months.collect{ |m| m.to_s + '月' }.insert(0, '')  
  14.   
  15.   
  16.    sheet1.row(0).concat(fixed_row)  
  17.    row1 = ['']  
  18.    (months.size - 1).times { row1 << ['用户数''金额''订单数'] }  
  19.   
  20.    sheet1.row(1).concat(row1.flatten!)  
  21.    row = 2  
  22.   
  23.    sheet1.row(row).insert(0, '全国')  
  24.   
  25.    months.each_with_index do |m, i|  
  26.      sheet1.row(row).insert(i*3 + 1, self.monthly_users_count(m))  
  27.      sheet1.row(row).insert(i*3 + 2, self.monthly_amount(m))  
  28.      sheet1.row(row).insert(i*3 + 3, self.monthly_orders_count(m))       
  29.    end  
  30.   
  31.    PROVINCE.each do |province|  
  32.      row += 1  
  33.      sheet1.row(row).insert(0, province)  
  34.      months.each_with_index do |m, i|  
  35.        sheet1.row(row).insert(i*3 + 1, self.monthly_users_count_by_province(m, province))  
  36.        sheet1.row(row).insert(i*3 + 2, self.monthly_amount_by_province(m, province))  
  37.        sheet1.row(row).insert(i*3 + 3, self.monthly_orders_count_by_province(m, province))  
  38.      end     
  39.    end  
  40.   
  41.    path = "tmp/phone_recharge.xls"  
  42.    book.write path  
  43.    path  
  44.  end  




17. inject({})
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. selected_conditions = base_conditions.inject({}) do |hash, data|  
  2.       hash[data.first] = data.last unless data.last.blank?  
  3.       hash  
  4.     end  


18.time_str.instance_of?
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. return time_str if time_str.instance_of? Time  



19.Person.instance_eval

[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Person.instance_eval do  
  2.     def species  
  3.       "Homo Sapien"  
  4.     end  
  5.   end  


20.class_eval

[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. class Foo  
  2.   end  
  3.   metaclass = (class << Foo; selfend)  
  4.   metaclass.class_eval do  
  5.       def species  
  6.         "Homo Sapien"  
  7.       end  
  8.     end  
  9.   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 程序员的梦中情人 

[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. def method_missing(method, *args)  
  2.   if method.to_s =~ /(.*)_with_cent$/  
  3.     attr_name = $1  
  4.     if self.respond_to?(attr_name)  
  5.       '%.2f' % (self.send(attr_name).to_f / 100.00)  
  6.     else  
  7.       super  
  8.     end  
  9.   end  
  10. end  



http://ruby-china.org/topics/3434

23.chomp
chomp方法是移除字符串尾部的分离符,例如\n,\r等...而gets默认的分离符是\n

24. hash.each_pair{|k,v|} & send()
       
[ruby] view plaincopy在CODE上查看代码片派生到我的代码片
  1. if bank_order.present?  
  2.           data_hash.each_pair { |k, v| bank_order.send("#{k}=", v) }  
  3.         else  
  4.           bank_order = BankOrder.new data_hash  
  5.         end  



25.config.middleware 通过 rake -T 可以查看, 在config/ - 去除不必的 middleware

26.1.day.ago.strftime('%Y%m%d’)

0 0
原创粉丝点击