Ruby on rails tips

976 views

Published on

some tips for ruby on rails

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
976
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
9
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Ruby on rails tips

  1. 1. Ruby on Railstips2013.04.29hebinbin.herokuapp.com
  2. 2. Object::try - 1Sometimes you write down the code like:user ? user.name : ‘No name’We can use try function to optimize codeuser.try(:name) || ‘No name’-> if user is not nil, display user.name-> if user is nil, nil.try(:name) will be nilnil || „No name‟ will be „No name‟
  3. 3. Object::try - 2Source Code:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/try.rbclass NilClassdef try(:args)nilendend
  4. 4. Object::presence1) nil.presence #=> nil2) [].presence #=> nil3) {}.presence #=> nil4) “” .presence #=> nil5) „‟ .presence #=> nil6) false.presence #=> nilSo you can change code likeparams[:name].present? ? params[:name] : ‘No name’Toparams[:name].presence || ‘No name’
  5. 5. Object::send -1class Hogedef test; puts ‘test’; endendHoge.new.test #=> „test‟Hoge.new.send(:test) #=> „test‟Hoge.new.send(„test‟) #=> „test‟Hoge.new.send(„testother‟) #=> NoMethodErrorSo object uses send to read method
  6. 6. Object::send -2Why we need to use send method:1. By using send method, we can read privatemethod. If you want to test private method, youcan use send methodclass Hogedef private_test; puts ‘private’; endprivate :private_testendHoge.new.private_test #=> NoMethodErrorHoge.new.send(:private_test) #=> „private‟
  7. 7. Object::send -3Why we need to use send method:2. We can pass method name as method parameter:class Hogedef send_test(method_name)self.send(method_name)enddef other_method‘test’endendHoge.new.send_test(:other_method) #=> „test‟
  8. 8. freezeWhen you do not want to change some constants orinstance variables in the program, you can use freeze.DAYS=[„Mon‟, „Tues‟, „Wes‟]DAYS << „Sat‟puts DAYS #=> =[„Mon‟, „Tues‟, „Wes‟, „Sat‟]DAYS=[„Mon‟, „Tues‟, „Wes‟].freezeDAYS << „Sat‟ #=> cant modify frozen Array(RuntimeError)
  9. 9. inject -1If you are familiar with C or Java, when you want toget sum from 1 to 10, maybe you will write ruby codelike:sum = 0(1..10).each { |i| sum = sum + I }puts sum #=> 55In ruby, you can use the other ways:puts (1..10).inject(0) { |sum, i| sum + I }
  10. 10. inject -2You can also use inject like:my_hash = { a: foo, b: bar }# => {:a=>"foo", :b=>"bar"}a_new_hash = my_hash.inject({}) { |h, (k, v)|h[k.upcase] = v.upcase; h }# => {:A=>"FOO", :B=>"BAR"}
  11. 11. tap -1When you want to change object itself and return thisobject, you can use tap method.The source code look like:class Objectdef tapyield(self)selfendend
  12. 12. tap -2ary = [3, 7, 6, 12]{}.tap {|h| ary.each{|x| h[x] = x**2} }# => {3=>9, 7=>49, 6=>36, 12=>144}{} changes itself to {3=>9, 7=>49, 6=>36, 12=>144}
  13. 13. tryrubyIf you do not want to install ruby on your pc,You can use online ruby:http://tryruby.org/levels/1/challenges/0
  14. 14. define numberIn ruby, if the number is too bigger to make mistakeeasily, you can write code like:Irb > 100_000# => 100000Irb >
  15. 15. HashWithIndifferentAccessIn some cases, you will find that:x = {"key1" => "value1"}x["key1"] #=> "value1"x[:key1] #=> nilHow can you use both x["key1"] and x[:key1] to get sameresult ?x = {"key1" => "val1"}x = x.with_indifferent_accessx[:key1] #=> "val1“x["key1"] #=> "val1"
  16. 16. assert_valid_keysSometimes, you will see some codes like:Image_tag(sym, options={})When you get options, nomrally we should check the keys areexisted or not. So you can use assert_valid_keysdef do_something(options = {})options.assert_valid_keys :x, :y# do the real somethingendIf the options contains any other keys, an ArgumentError will beraised.PS: the better way should be delete other keys.
  17. 17. Extend ruby class -1Back to example which we given before, you want tocreate a new method for hash to get_valid_keys:class Hashdef get_valid_keys(*args)endendSo in ruby on rails, how to extend it ?
  18. 18. Extend ruby class -21. Put the code into lib/core_ext/hash.rbYou also need the following code in your initializerconfig:Dir[File.join(Rails.root, "lib", "core_ext", "*.rb")].each{|l| require l }At last, restart your app.2. Put the code into config/initializers/hash.rbThen restart your app.
  19. 19. Set union• Join two arrays and remove duplicates with pipeoperator (|)[ "a", "b", "c" ] | [ "c", "d", "a" ]# => ["a", "b", "c", "d"]
  20. 20. RubyInlineWhen you want to run C or C++ language in your rubycode to improve performance , plz check followingwebsite.https://github.com/seattlerb/rubyinline
  21. 21. Use chainIn ruby, we can use chain to avoid using tempvariables for example:#bad codehoge = Hoge.newputs hoge.name#good codeputs Hoge.new.name
  22. 22. performance1. Ruby is an interpreted language and interpretedlanguages will tend to be slower than compiledones2. Ruby uses garbage collection3. Ruby (with the exception of JRuby) does notsupport true multithreading.4. Ruby is heavy memory.5. Instantiating too many active record objects is aplace where rails apps memory footprint reallygrows. (Flyweight Pattern:http://en.wikipedia.org/wiki/Flyweight_pattern#Example_in_Ruby)
  23. 23. Why ruby does not support turemulti-threading?• In Ruby you have got Global Interpreter Lock, soonly one Thread can work at a time. So, Ruby spendmany time to manage which Thread should be firedat a moment (thread scheduling). So in yourcase, when there is no any IO it will be slower!• You can use Rubinius or JRuby to use real Threads.• Jruby implements threads with JVM threads, whichin turn uses real threads.

×