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

这篇文章主要介绍了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 人如其名, 随时可以添加属性
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

以上就是Ruby的25个编程细节(技巧、实用代码段)的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 脚本专栏