首页 > 学院 > 开发设计 > 正文

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

2019-10-26 19:26:57
字体:
来源:转载
供稿:网友

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 人如其名, 随时可以添加属性
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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表