当前位置:首页 > 开发 > 编程语言 > Ruby > 正文

ruby 小技巧

发表于: 2014-02-23   作者:52jobs   来源:转载   浏览:
摘要: #Track 1: The C in MVC #irb Mix Tape http://errtheblog.com/posts/24-irb-mix-tape #深入讲解 app http://pragmaticstudio.com/blog/2006/4/4/running-your-rails-app-headless $ ruby script/console #Loading
#Track 1: The C in MVC  #irb Mix Tape http://errtheblog.com/posts/24-irb-mix-tape
#深入讲解 app http://pragmaticstudio.com/blog/2006/4/4/running-your-rails-app-headless

$ ruby script/console
#Loading development environment.
>> app.url_for(:controller => 'stories', :action => 'show', :id => '10002')
=> "http://www.example.com/stories/10002" 
>> app.get '/stories/10002'   => 200
>> app.assigns(:story)        => #<Story:0x24aad0c ... >
>> app.path                   => "/stories/10002" 
>> app.reset!                 => nil
>> app.get '/yeah/right/dude' => 404
>> app.post '/account/login', { :username => 'defunkt', :password => 'razzletaz' }  => 200
>> app.cookies                => {"_session_id"=>"9d1c014f42881524ff6cb81fb5b594bc"}

>>app.products_path                =>"/products"
>>app.get _                    =>200
>>app.class                    =>ActionController::Integration::Session
>>app.response.headers
>>app.assigns(:producs) #指controller中是不含有 @products的实例变量
app通常可用来用集成测试 intergration test
与app 相关的
assigns - Any objects that are stored as instance variables in actions for use in views.
cookies - Any cookies that are set.
flash - Any objects living in the flash.
session - Any object living in session variables.

flash["gordon"]               flash[:gordon]
session["shmession"]          session[:shmession]
cookies["are_good_for_u"]     cookies[:are_good_for_u]
 
# Because you can't use assigns[:something] for historical reasons:
assigns["something"]          assigns(:something)
可以访问以下三个实例变量

@controller - The controller processing the request
@request - The request
@response - The response




#Track 2: The Help in MVC
$ ruby script/console
Loading development environment.
>> helper.pluralize 2, "story"  => "2 stories" 
>> helper.submit_tag            => "<input name=\"commit\" type=\"submit\" value=\"Save changes\" />" 
>> helper.visual_effect :blindUp, 'post'  => "new Effect.BlindUp(\"post\",{});" 

#Track 3: Context
Spawn irb subsessions in the context of an object
$ ruby script/console 
Loading development environment.
>> irb Story
>> self             => Story
>> find(:first)     => #<Story:0x2427c2c ... >
>> quit
>> irb Story.find(:first)
>> title            => "Mail-Order Desserts" 
>> quit             => #<IRB::Irb: @scanner=#<RubyLex:0x249a36c>, @context=#<IRB::Context:0x249e534>, @signal_status=:IN_EVAL>
>> irb app
>> host             => "www.example.com" 
It’s like you’re actually in the object. Any methods you call are getting called on the object whose context and privacy you have invaded. Saves some typing and gets you in with @instance_variables, too. Remember: you can use this in normal irb as well.


Track 4: Sandboxin’
$ ruby script/console --sandbox           =>Loading development environment in sandbox.
>> story = Story.find(:first)             => #<story:0x244f0ec>
>> story.title                            => "Mail-Order Desserts" 
>> story.title = "Snail Mail Droooolz!"   => "Snail Mail Droooolz!" 
>> story.save                             => true
>> Story.find(:first).title               => "Snail Mail Droooolz!" 
>> quit
$ ruby script/console                     =>Loading development environment.
>> Story.find(:first).title               => "Mail-Order Desserts" 


Track 5: Watson the Underbar
>> 1 + 1    => 2
>> _        => 2
>> _ * _    => 4
   


Track 6 – Auto-completion in IRB 看动填充
"hello".to_<double TAB here 两次tab >
.to_a    .to_f    .to_i    .to_s    .to_str  .to_sym

Track 7 – Map by Method http://drnicutilities.rubyforge.org/ 使用新gem 增强 map
list = ['1',  '2', '3']        => ["1", "2", "3"]
list.map {|item| item.to_i}    => [1, 2, 3]
list.map &:to_i                => [1, 2, 3]
["1","2","3"]. map_by_to_i     => [1,2,3]

ActiveRecord 也要可使用 map by method
$ gem install map_by_method
$ console
> require 'map_by_method'  # stick this in your environment.rb for Rails
> user = User.find_by_name "Dr Nic"
> user.companies.map_by_name         => ['Dr Nic Academy', 'Dr Ni']
> user.companies.map_by_id_and_name  => [[1, 'Dr Nic Academy'], [9, 'Dr N']]
>> User.find(:all).map_id_and_firstname => [[1, "Glenda"], [2, "Brenda"], [3, "Yas"]]

新gem to_acitiverecord
$ gem install to_activerecord
$ console
> require 'to_activerecord'  # stick this in your environment.rb for Rails
> [1,2,3].to_user.map_by_name   => ['Dr Nic', 'Banjo', 'Nancy']
传统写法是 User.find(ids).map_by_name


Track 7 – MethodFinder/Object.what? 注意,经验证,好像只适合用数字  
gem install what_methods    require 'what_methods'
> 3.45.what? 3
3.45.truncate == 3
3.45.to_i == 3
=> ["truncate", "to_i", "prec_i", "floor", "to_int", "round"]

Track 8 The explicit Ruby metaclass
$ gem install magic_metaclass
$ irb
require 'rubygems'
require 'magic_metaclass'
class Person; end
Person            # => Person
PersonMetaclass   # => #<Class:Person>
PersonClass       # => #<Class:Person>
PersonEigenclass  # => #<Class:Person>
PersonEigen       # => #<Class:Person>


Track 9 经典用法
$ script/console production
$ script/console test
$ script/console development

>> @george = Person.find_by_name('George')
>> @bob = Person.find_by_name('Bob')
>> @bob.friends << @george
>> puts @bob.to_yaml
>> y @bob
>> reload!

ruby 小技巧

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号