O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

InactiveSupport

2.038 visualizações

Publicada em

Publicada em: Tecnologia
  • If you are looking for customer-oriented academic and research paper writing service try ⇒⇒⇒ WRITE-MY-PAPER.net ⇐⇐⇐ liked them A LOTTT Really nice solutions for the last-day papers
       Responder 
    Tem certeza que deseja  Sim  Não
    Insira sua mensagem aqui

InactiveSupport

  1. 1. >> 'foo'.tapp "foo" => "foo"
  2. 2. class Object def tapp require 'pp' tap { pp self } end end
  3. 3. (1..3).map {|i| i ** 2 }.inject(&:+) tmp = (1..3).map {|i| i ** 2 } pp tmp tmp.inject(&:+)
  4. 4. (1..3).map {|i| i ** 2 }.tap {|v| pp v }.inject(&:+) (1..3).map {|i| i ** 2 }.tapp.inject(&:+)
  5. 5. >> s = {:foo => {:bar => 1}}.to_struct => #<OpenStruct foo=#<OpenStruct bar=1>> >> s.foo.bar => 1
  6. 6. require 'ostruct' class Hash def to_struct OpenStruct.new(inject({}) {|h, (k, v)| h.merge(k => v.is_a?(Hash) ? v.to_struct : v) }) end end
  7. 7. CONFIG = { :admin => { :name => 'yasuo' }, ... } CONFIG[:admin][:name]
  8. 8. CONFIG = OpenStruct.new( :admin => OpenStruct.new( :name => 'yasuo' ), ... ) CONFIG.admin.name
  9. 9. CONFIG = { :admin => { :name => 'yasuo' }, ... }.to_struct CONFIG.admin.name
  10. 10. ✓ ✓ ✓ ✓
  11. 11. >> h = {:a => 1, :b => 2, :c => 3} => {:a=>1, :b=>2, :c=>3} >> h.pairs_at(:a, :c) => {:a=>1, :c=>3}
  12. 12. class Hash def pairs_at(*keys) keys.zip(values_at(*keys)).inject(self.class.new) {|h, (k, v)| h.merge(k => v) } end end
  13. 13. class UsersController def create u = User.new(params[:user]) ... end end
  14. 14. class UsersController def create u = User.new( :name => params[:user][:name], :age => params[:user][:age] ) ... end end
  15. 15. class UsersController def create u = User.new( params[:user].pairs_at(:name, :age) ) ... end end
  16. 16. class UsersController def create u = User.new( params[:user].slice(:name, :age) ) ... end end
  17. 17. >> 'foo'.try(:capitalize) => "Foo" >> 'foo'.try(:hoge) => nil
  18. 18. class Object def try(method, *args, &block) respond_to?(method) ? send(method, *args, &block) : nil end end
  19. 19. <%=h @user.sector.name %> <%=h @user.sector && @user.sector.name %> <%=h @user.sector.try(:name) %>
  20. 20. >> nil.try(:hoge) => nil >> 1.try(:hoge) NoMethodError: undefined method `hoge' for 1:Fixnum
  21. 21. class UsersController def create irb ... end end
  22. 22. class Object def irb require 'irb' IRB.setup nil IRB::Irb.new(IRB::WorkSpace.new(binding)).tap {|i| IRB.conf[:MAIN_CONTEXT] = i.context }.eval_input end end
  23. 23. >> 'users'.what? 'User' "users".classify == "User" => ["classify"] >> 'User'.what? 'users' "User".tableize == "users" => ["tableize"]
  24. 24. ✓ ✓ ✓ ✓
  25. 25. ✓ ✓

×