麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁(yè) > 編程 > Ruby > 正文

Ruby的25個(gè)編程細(xì)節(jié)(技巧、實(shí)用代碼段)

2020-10-29 19:38:48
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

1.try 永遠(yuǎn)不會(huì)拋出異常 在 沒(méi)有的時(shí)候 返回 nil

復(fù)制代碼 代碼如下:

province_id = Province.find_by_name(prov).try(:id) 

2.find(:first, :condotions) 方法 不言而與

復(fù)制代碼 代碼如下:

mobile_info = MobileInfo.find(:first, :conditions => ["mobile_num = ? ", mobile_num.to_i]) 

3.find(:all, :select, :conditions)

復(fù)制代碼 代碼如下:

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.發(fā)送post請(qǐng)求 可以在shell中執(zhí)行 

復(fù)制代碼 代碼如下:

curl -d "channel=中信異度支付&action_type=娛人節(jié)-手機(jī)充值&user_indicate=13911731997&original_amount=10000" http://xx.xxx.xxx:3000/search.json 

5.Ruby 中純數(shù)據(jù)結(jié)構(gòu) ( Struct 與 OpenStruct )

講一下它倆之間的區(qū)別:

Struct 需要開(kāi)頭明確聲明字段; 而 OpenStruct 人如其名, 隨時(shí)可以添加屬性
Struct 性能優(yōu)秀; 而 OpenStruct 差點(diǎn), 具體的性能差距可看這里:http://stackoverflow.com/questions/1177594/ruby-struct-vs-openstruct
Struct 是 Ruby 解釋器內(nèi)置, 用 C 實(shí)現(xiàn); OpenStruct 是 Ruby 標(biāo)準(zhǔn)庫(kù), Ruby 實(shí)現(xiàn)
API 不同: Struct API 與 OpenStruct

6. MIme::Type.register

復(fù)制代碼 代碼如下:

Mime::Type.register "application/json", :ejson 
config/initializers/mime_types.rb

7.config/initializers/secure_problem_solved.rb

復(fù)制代碼 代碼如下:

ActiveSupport::CoreExtensions::Hash::Conversions::XML_PARSING.delete('symbol') 
ActiveSupport::CoreExtensions::Hash::Conversions::XML_PARSING.delete('yaml') 

8.config/initializers/new_rails_default.rb

復(fù)制代碼 代碼如下:

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 緩存

復(fù)制代碼 代碼如下:

@_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.聯(lián)合索引

復(fù)制代碼 代碼如下:

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

復(fù)制代碼 代碼如下:

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

復(fù)制代碼 代碼如下:

m_order[:merchant_id] = (merchant.instance_of? MplusMerchant) ? merchant.id : merchant 

15.will_paginate rails

安裝之后需要修改config/environment.rb文件
在文件的最后添加:

復(fù)制代碼 代碼如下:

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'

最好有個(gè)include

16. # Excel Generator

復(fù)制代碼 代碼如下:

gem 'spreadsheet', '~> 0.7.3'
 PROVINCE = %w{ 安徽  北京  福建  甘肅  廣東  廣西  貴州  海南  河北  河南  黑龍江 湖北
      湖南  吉林  江蘇  江西  遼寧  內(nèi)蒙古 寧夏  青海  山東  山西  陜西  上海
      四川  天津  西藏   新疆  云南  浙江  重慶 }

  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 << ['用戶數(shù)', '金額', '訂單數(shù)'] }

    sheet1.row(1).concat(row1.flatten!)
    row = 2

    sheet1.row(row).insert(0, '全國(guó)')

    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({})

復(fù)制代碼 代碼如下:

selected_conditions = base_conditions.inject({}) do |hash, data|
      hash[data.first] = data.last unless data.last.blank?
      hash
    end

18.time_str.instance_of?

復(fù)制代碼 代碼如下:

return time_str if time_str.instance_of? Time

19.Person.instance_eval

復(fù)制代碼 代碼如下:

Person.instance_eval do
    def species
      "Homo Sapien"
    end
  end

20.class_eval

復(fù)制代碼 代碼如下:

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
因?yàn)閛bj對(duì)象沒(méi)法響應(yīng)talk這個(gè)消息,如果使用 respond_to? 這個(gè)方法,就可以實(shí)現(xiàn)判斷對(duì)象能否響應(yīng)給定的消息了

復(fù)制代碼 代碼如下:

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,一個(gè) Ruby 程序員的夢(mèng)中情人

復(fù)制代碼 代碼如下:

    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默認(rèn)的分離符是/n

24. hash.each_pair{|k,v|} & send()

復(fù)制代碼 代碼如下:

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 通過(guò) rake -T 可以查看, 在config/ - 去除不必的 middleware

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

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 九色在线78m | 亚洲自拍第二页 | 国产精品久久久免费看 | 激情在线观看视频 | 中文在线观看免费视频 | 久久久久久久久久久久久久久久久久 | 一级毛片电影院 | 毛片视频播放 | av老司机久久 | 久久人人爽人人爽人人片av高清 | 黄色片视频在线观看 | 日本网站在线播放 | 精品国产一区二区三区免费 | 香蕉国产片| 黄色大片在线观看 | 欧美中文字幕在线视频 | 午夜视频大全 | 毛片网站网址 | 精品久久久久久久久久久aⅴ | 91一级毛片 | 性少妇chinesevideo | 国产午夜精品理论片a级探花 | 成年人视频在线免费观看 | 暴力强行进如hdxxx | xxxxhdvideosex| 亚洲第一成人av | 鲁久久 | 日本最新免费二区三区 | 91 成人| 青青草成人免费视频在线 | 国产成年人在线观看 | www中文在线 | 亚洲欧美日韩免费 | 99最新网址 | 久久国产亚洲视频 | 久久久久久久久国产 | 暖暖免费观看高清完整版电影 | 国产韩国精品一区二区三区久久 | 牛牛a级毛片在线播放 | 精国品产一区二区三区有限公司 | 91美女视频在线观看 |