Ruby's 25 programming details (tips and practical code segments), ruby25

Source: Internet
Author: User
Tags iso 8601 iso 8601 format

Ruby's 25 programming details (tips and practical code segments), ruby25

1. try will never throw an exception and return nil if there is no
The Code is as follows:
Province_id = Province. find_by_name (prov). try (: id)

2. The find (: first,: condotions) method does not speak
The Code is as follows:
Mobile_info = MobileInfo. find (: first,: conditions => ["mobile_num =? ", Mobile_num.to_ I])

3. find (: all,: select,: conditions)
The Code is as follows:
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. change_value_id}. compact

Support_amount_s = ChangeValue. find (: all,: select => "price",: conditions => ["id in (?) ", Support_amount_a]) \
. Map {| cv. try (: price). to_ I}. compact

4. the post request can be executed in shell.

The Code is as follows:
Curl-d "channel = CITIC differential payment & action_type = entertainment festival-mobile phone recharge & user_indicate = 13911731997 & original_amount = 10000" http://xx.xxx.xxx: 3000/search. json

5. Ruby pure data structure (Struct and OpenStruct)

Let's talk about the differences between them:

Fields must be explicitly declared at the beginning of Struct. OpenStruct users can add attributes at any time as their names
Struct performance is good; and OpenStruct almost, the specific performance gap can be seen here: http://stackoverflow.com/questions/1177594/ruby-struct-vs-openstruct
Struct is built into the Ruby interpreter and implemented in C; OpenStruct is the Ruby standard library and Ruby implementation
Different APIs: Struct API and OpenStruct

6. MIme: Type. register

The Code is as follows:
Mime: Type. register "application/json",: ejson
Config/initializers/mime_types.rb

7. config/initializers/secure_problem_solved.rb
The Code is as follows:
ActiveSupport: CoreExtensions: Hash: Conversions: XML_PARSING.delete ('symbol ')
ActiveSupport: CoreExtensions: Hash: Conversions: XML_PARSING.delete ('yaml ')

8. config/initializers/new_rails_default.rb
The Code is as follows:
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
The Code is as follows:
@ _ 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. Joint Index
The Code is as follows:
Gem 'composite _ primary_keys ', '6. 123'

Https://github.com/momoplan

0. Hash assert_valid_keys White List


11. puma-C puma_service_qa.rb

12. pow

13. Time

The Code is as follows:
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

The Code is as follows:
M_order [: merchant_id] = (merchant. instance_of? MplusMerchant )? Merchant. id: merchant

15. will_paginate rails

After installation, modify the config/environment. rb file.
Add at the end of the file:
The Code is as follows:
Require 'will _ paginate'
Modify the index method in the controller file:
# @ Products = Product. find (: all)
@ Products = Product. paginate: page => params [: page],
: Per_page => 2
. Pagination
= Will_paginate @ mplus_orders,: class => 'digg _ pagination'

It is better to have an include

16. # Excel Generator
The Code is as follows:
Gem 'readsheet ',' ~> 0.7.3'
PROVINCE = % w {Anhui Beijing Fujian Gansu Guangdong Guangxi Guizhou Hainan Hebei Henan Heilongjiang Hubei
Hunan Jilin Jiangsu Jiangxi Liaoning Inner Mongolia Ningxia Qinghai Shandong Shanxi Shaanxi Shanghai
Sichuan, Tianjin, Tibet, Xinjiang, Yunnan, Zhejiang, Chongqing}

MONTH = 1. upto (12). to_a

Def self. total_to_xls (year = '201312', 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. to_s + 'month'}. insert (0 ,'')


Sheet1.row (0). concat (fixed_row)
Row1 = ['']
(Months. size-1). times {row1 <['users', 'amount', 'order singles']}

Sheet1.row (1). concat (row1.flatten !)
Row = 2

Sheet1.row (row). insert (0, 'China ')

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 ({})
The Code is as follows:
Selected_conditions = base_conditions.inject ({}) do | hash, data |
Hash [data. first] = data. last unless data. last. blank?
Hash
End

18. time_str.instance_of?

The Code is as follows:
Return time_str if time_str.instance_of? Time

19. Person. instance_eval

The Code is as follows:
Person. instance_eval do
Def species
"Homo Sapien"
End
End

20. class_eval
The Code is as follows:
Class Foo
End
Metaclass = (class <Foo; self; end)
Metaclass. class_eval do
Def species
"Homo Sapien"
End
End
End



21. respond_to? In Ruby? And send usage
Http://galeki.is-programmer.com/posts/183.html
Because the obj object cannot respond to the talk message, if respond_to? This method can be used to determine whether an object can respond to a given message.
The Code is as follows:
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, a Ruby programmer's dream lover
The Code is as follows:
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

The chomp method removes the delimiters at the end of a string, for example, \ n, \ r, etc.... while the default delimiters of gets are \ n.

24. hash. each_pair {| k, v |}& send ()
The Code is as follows:
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 can be viewed through rake-T. In config/-Remove unnecessary middleware

26.1.day.ago.strftime ('% Y % m % D ')


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.