This article mainly introduces Ruby's 25 programming details (tips, practical code snippet), this article directly gives the topic and the corresponding code, needs the friend may refer to under
1.try never throws an exception to return nil when not
The code is as follows:
province_id = Province.find_by_name (Prov). Try (: ID)
2.find (: A: Condotions) method does not speak but with
The code is as follows:
Mobile_info = Mobileinfo.find (: I,: 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| cv.change_value_id}.compact
support_amount_s = Changevalue.find (: All,:select => "price": Conditions => ["IDs in (?)", Support_amount_a])
. map {|cv| cv.try (:p rice). To_i}.compact
4. Send POST request can be executed in shell
The code is as follows:
Curl-d "channel= Citic different pay &action_type= Entertainment people's Day-mobile recharge &user_indicate=13911731997&original_amount=10000" http:// Xx.xxx.xxx:3000/search.json
5.Ruby Pure Data structure (STRUCT and openstruct)
Tell the difference between them:
Struct need to begin with a clear declaration of the field; And openstruct people like their name, you can add attributes at any time
Excellent Struct performance; And Openstruct almost, the specific performance gap can be seen here: http://stackoverflow.com/questions/1177594/ruby-struct-vs-openstruct
Struct is a Ruby interpreter built in, implemented in C; Openstruct is the Ruby Standard library, Ruby implements
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 the ISO 8601 format for JSON serialized The Times and dates.
Activesupport.use_standard_json_time_format = True
# Don ' t escape HTML entities in JSON, leave this for the #json_escape helper.
# If you ' re including raw JSON into 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. Federated Index
The code is as follows:
Gem ' Composite_primary_keys ', ' 6.0.1 '
Https://github.com/momoplan
0.Hash Assert_valid_keys White List
11.puma-c puma_service_qa.rb
12.pow
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
CONFIG/ENVIRONMENT.RB files need to be modified after installation
At the end of the file add:
The code is as follows:
Require ' will_paginate '
To modify the index method in the controller file:
# @products = Product.find (: All)
@products = Product.paginate:p Age => params[:p age],
:p Er_page => 2
. pagination
= Will_paginate @mplus_orders,: Class => ' digg_pagination '
Better have an include
# Excel Generator
The code is as follows:
Gem ' spreadsheet ', ' ~> 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 (in). to_a
Def self.total_to_xls (year = ' = ', 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 + ' month '}.insert (0, ')
Sheet1.row (0). Concat (Fixed_row)
Row1 = [']
(Months.size-1). Times {Row1 << [' Number of users ', ' Amount ', ' Order number ']}
Sheet1.row (1). Concat (row1.flatten!)
row = 2
Sheet1.row (Row). Insert (0, ' national ')
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
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.Ruby in respond_to? And the use of send
Http://galeki.is-programmer.com/posts/183.html
Because obj objects cannot respond to talk this message, if you use respond_to? This method enables you 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 = $
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 is to remove the trailing character of the string, such as N,r ... and gets the default separator is n
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 through Rake-t can be viewed in config/-removal of unnecessary middleware
26.1.day.ago.strftime ('%y%m%d ')