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=>"DISTINCTchange_value_id", :conditions=>["status=1andmerchant_id=?andprovince_id=?andchannel_idin(selectidfromchannelswherestatus=1)", merchant_id,province_id]).map{|cv|cv.change_value_id}.compact support_amount_s=ChangeValue.find(:all,:select=>"price",:conditions=>["idin(?)",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人如其名,随时可以添加属性
Struct性能优秀;而OpenStruct差点,具体的性能差距可看这里:http://stackoverflow.com/questions/1177594/ruby-struct-vs-openstruct
Struct是Ruby解释器内置,用C实现;OpenStruct是Ruby标准库,Ruby实现
API不同:StructAPI与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
ifdefined?(ActiveRecord) #IncludeActiveRecordclassnameasrootforJSONserializedoutput. ActiveRecord::Base.include_root_in_json=true
#Storethefullclassname(includingmodulenamespace)inSTItypecolumn. ActiveRecord::Base.store_full_sti_class=true end
ActionController::Routing.generate_best_match=false
#UseISO8601formatforJSONserializedtimesanddates. ActiveSupport.use_standard_json_time_format=true
#Don'tescapeHTMLentitiesinJSON,leavethatforthe#json_escapehelper. #ifyou'reincludingrawjsoninanHTMLpage. ActiveSupport.escape_html_entities_in_json=false