`
xiaoheliushuiya
  • 浏览: 404562 次
文章分类
社区版块
存档分类
最新评论

Ruby 一些常用的细节

阅读更多



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


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 APIOpenStruct
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'

最好有个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 = {})
    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?
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



21.
Ruby中 respond_to? 和 send 的用法
http://galeki.is-programmer.com/posts/183.html
因为obj对象没法响应talk这个消息,如果使用 respond_to? 这个方法,就可以实现判断对象能否响应给定的消息了
obj =Object.new
ifobj.respond_to?("talk")
obj.talk
else
puts"Sorry, object can't talk!"
end

request =gets.chomp

ifbook.respond_to?(request)
putsbook.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



http://ruby-china.org/topics/3434

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’)


分享到:
评论

相关推荐

    Ruby程序设计语言 (涵盖Ruby 1.8和1.9)源代码

    本书首先通过一个快速指南带您熟悉这门语言,然后彻底解释它的细节,包括:  Ruby程序的词法和句法结构  数据类型和对象  表达式和操作符  语句和控制结构  Method、proc、lambda和closure  类和模块  反射和...

    Ruby元编程-中文

    通过分析案例、讲解例题、回顾Ruby代码库的实现细节,作者不仅向读者展示了Ruby编程的优势和Ruby特有的解决问题的方式,更详细开列出发挥其优势的技巧和常用的Ruby设计模式。Ruby之父松本行弘作 序推荐。

    ruby元编程

    更详细列出了发挥其优势的技巧和常用的Ruby设计模式 Ruby创始人松本行弘作序推荐 "&gt;《Ruby元编程》以案例形式循序渐进地介绍了Ruby特有的实用编程技巧 元编程 通过分析案例 讲解例题 回顾Ruby代码库的实现细节 ...

    ruby语言教程资源案例

    以下是一些Ruby资源简介: 官方文档:Ruby的官方文档是学习Ruby编程的基础材料。它提供了详细的语法说明、类和方法参考以及最佳实践指南等。 社区资源:Ruby社区非常活跃,有许多在线资源和活动。例如,Ruby Koans...

    Ruby高级编程教程-世界顶级高校教材(完整版827页)

    它从一些关于让Ruby在您的系统上运行的注释开始,然后是一个简短的章节,介绍Ruby特有的一些术语和概念。本章还包括足够多的基本语法,以便其他章节有意义。本教程的其余部分是对该语言的自上而下的研究。在这里,...

    Ruby On Rails开发从头来系列教程(chm)

    摘要:一直想尝试Ruby On Rails,但是因为对apache,mysql都不熟,对Rails的环境搭建更是没信心,所以一直没有开始,从知道了InstantRails后,终于在windows上搭建了Ruby On Rails开发环境,开始了Rails的学习。...

    Ruby元编程【英文版】

    通过分析案例、讲解例题、回顾Ruby代码库的实现细节,作者不仅向读者展示了Ruby编程的优势和Ruby特有的解决问题的方式,更详细开列出发挥其优势的技巧和常用的Ruby设计模式。Ruby之父松本行弘作 序推荐。(引自豆瓣...

    Ruby代码浏览器SystemBrowserClient.zip

    System Browser Client 是一个用来浏览 Ruby 代码桌面应用程序,只需点击,就能获取一个模块或类的细节,并查看其命名空间或看到一个方法的来源。浏览器不显示实时行为的信息。也就是说,如果你启动浏览器后,再定义...

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

    主要介绍了Ruby的25个编程细节(技巧、实用代码段),本文直接给出主题和相应代码,需要的朋友可以参考下

    Web开发大全:Ruby on Rails版.part1

    本书基于ruby on rails,详细讲述web开发中所涉及的各个主要环节,并且将作者在开发过程中积累的经验和技巧与读者分享。在本书的每个章节中,都有与内容配合的详细实例,帮助读者快速理解并掌握使用ruby on rails...

    Web开发大全:Ruby on Rails版.part2

    本书基于ruby on rails,详细讲述web开发中所涉及的各个主要环节,并且将作者在开发过程中积累的经验和技巧与读者分享。在本书的每个章节中,都有与内容配合的详细实例,帮助读者快速理解并掌握使用ruby on rails...

    ruby元编程之method_missing的一个使用细节

    主要介绍了ruby元编程之method_missing的一个使用细节,本文介绍在使用method_missing时造成死循环的一个现象,需要的朋友可以参考下

    RubyMine(Ruby编码编辑器) v7.0.4 官方版.zip

    JetBrains公司的RubyMine IDE提供了一个全面的Ruby代码编辑器,了解动态语言的细节,并提供智能编码辅助,智能代码重构和代码分析能力。简单的项目配置,自动Ruby Gems的管理,耙支持 - 它有一切一个Ruby开发人员...

    Ruby on Rails迁移时的一些注意事项

    主要介绍了Ruby on Rails迁移时的一些注意事项,包括建议的使用change方法取代up与down方法等细节,需要的朋友可以参考下

    Ruby中使用each和collect进行迭代的用法

    让我们来看看这些细节. Ruby each 迭代: 每个迭代器返回一个数组的所有元素或哈希. 语法: collection.each do |variable| code end 在集合中的每个元素执行的代码。这里收集可能是一个数组或ruby哈希. 例子: #!/...

    rgl:RGL是用于Ruby中图形数据结构和算法的框架

    一个接口,用于使用隐藏图形数据结构实现细节的通用接口访问图形结构。 该接口由模块{RGL :: Graph}定义,应包含在具体的类中。 用于遍历图形的标准通用接口{RGL :: GraphIterator} RGL提供了一些符合该接口的...

    react-blog:React + Redux + Ruby On Rails 实现的博客系统

    基于 React 实现的个人博客 本项是使用 React 实现...目前项目已经能使用,但是还有很多细节需要完善,代码也需要优化和重构,感兴趣的朋友可以 start 或者加 follow,后面我会持续更新。 项目部署 因为涉及到 Ruby on

    RubyDrop:滚动你自己的用 Ruby 编写的类似 Dropbox 的克隆

    Ruby滴剂RubyDrop 是我的第一个 Ruby 项目,旨在成为一个开源的、自己动手的、使用 Git 作为后端的 Dropbox 克隆。 还有很多细节需要解决,代码可能有点乱,所以你必须忍受我(这是一个过程)。先决条件RubyRuby 1.9...

    reactomatic:Reactomatic是Ruby的Reactor模式的实现

    React式 Reactomatic是Ruby的实现。 它建立在出色的宝石。安装将此行添加到您的应用程序的Gemfile中: gem 'reactomatic'然后执行: $ bundle或将其自己安装为: $ gem install reactomatic电抗器Reactor类是...

Global site tag (gtag.js) - Google Analytics