Ruby的25个编程细节(技巧、实用代码段)

2019-09-25 09:42:12于丽

# 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 = {})