Rubyこまごました点

9938 ワード

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://10.150.150.151:3000/search.json
5.Rubyにおける純データ構造(StructとOpenStruct)
2つの違いを説明します
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
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
10.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'


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?, is_a?
return time_str if time_str.instance_of? Time
return time_str if time_str.is_a? 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
  def self.method_missing(method_sym, *arguments, &block)
    if method_sym.to_s =~ /^n_(.*)$/
      #    Channel.n_JunBao        
      # Bug fix:      channel_name = 19Pay   Yj19Pay   
      #    Channel.n_19Pay,    Configs::Yj19PayChannel    ChannelName      
      process_class_name = ($1 == '19Pay' ? "Yj19Pay" : $1)
      find_by_process_class(process_class_name)
    else
      super
    end
  end
  def method_missing(meth, *args, &blk)
    #    suspending? ending? init? force?
    if meth.to_s =~ /(.*)\?$/
      return is_status?($1)
    end
    #    stat_to_init stat_to_suspending stat_to_ending stat_to_force
    if meth.to_s =~ /^stat_to_(.*)$/
      return trans_stat_to($1)
    end
    #     super
    super
  end

http://ruby-china.org/topics/3434
23.chomp
chompメソッドは、文字列の末尾の分離子を除去することです.例えば、rなど...getsのデフォルトの分離子は
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’)
27.<%=h change_retry.order_record.try(:created_time) %> (h)
Rails 3以前のバージョンでは、<%=hevent.を使用する必要があります.name%>このようなHTMLは、XSSネットワークの攻撃を防ぐために逸脱します.Rails 3以降はプリセットが抜けます.逸脱しない場合は<%=rawevent.を使用します.name%>または<%=event.name.html_safe! %>.ネットワークセキュリティの章では、XSSについてさらに説明します.
28.  block , block_given?
def f1
 yield if block_given?
end

def f2(&p)
  p.call if block_given?
end

29.godモニタ
http://noops.me/?p=133
30.Railsプロセスのメモリ漏洩を監視するテクニック
http://robbin.iteye.com/blog/307271
https://ruby-china.org/topics/15853
http://blog.linjunhalida.com/blog/ruby-memory-leak-debug/
http://blog.linjunhalida.com/blog/librr-debug-cpu-usage-high/
gem
https://github.com/binarylogic/memorylogic https://github.com/noahd1/oink
31.nginx構成説明
https://github.com/biti/passenger-doc-zh/wiki/Passenger%E7%94%A8%E6%88%B7%E6%89%8B%E5%86%8Cnginx%E7%89%88
32.passengerの使用状況の表示
rvmsudo passenger-memory-stats 
33.ResqueとSidekiqの違い
http://grantcss.com/blog/2015/01/21/difference-between-resque-and-sidekiq/
34. secret_token
A secret is required to generate an integrity hash for cookie session data. Use config.secret_token = "some secret phrase of at least 30 characters"in config/initializers/secret_token.rb
OK
rake secret