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 人如其名,随时可以添加属性 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. ActionController::Routing.generate_best_match = false # Use ISO 8601 format for JSON serialized times and dates. # Don't escape HTML entities in JSON,leave that for the #json_escape helper. 9.MemCacheStore 缓存 复制代码 代码如下: @_cache = ActiveSupport::Cache::MemCacheStore.new( CONFIG['host'],{ :namespace => "#{CONFIG['namespace']}::#{@name}" } ) localhost::callback_lock @_cache.write(pay_channel.channel_id,'true') 10.联合索引 复制代码 代码如下: gem 'composite_primary_keys','6.0.1' https://github.com/momoplan 0.Hash assert_valid_keys 白名单
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 = {}) fixed_row = months.collect{ |m| m.to_s + '月' }.insert(0,'')
sheet1.row(1).concat(row1.flatten!) sheet1.row(row).insert(0,'全国') months.each_with_index do |m,i| PROVINCE.each do |province| path = "tmp/phone_recharge.xls" 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
复制代码 代码如下: 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') (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |