`
52jobs
  • 浏览: 11502 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

ruby 小技巧

阅读更多
#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小技巧分享

    ### Ruby小技巧分享 在日常开发中,Ruby以其简洁优雅的语法著称,它提供了许多实用的功能和特性,使得编写代码既高效又有趣。本文将详细介绍几个常用的Ruby小技巧,帮助开发者更好地理解和运用Ruby。 #### 1. 代码...

    Ruby-Ruby技巧惯用Ruby重构和最佳实践

    本文将深入探讨Ruby中的关键技巧、重构方法以及遵循的代码风格指南。 一、Ruby技巧 1. 块和迭代器:Ruby中的块(blocks)和迭代器(iterators)是其强大之处。使用`each`、`map`等方法可以简洁地遍历集合。例如,`...

    ruby技巧

    在 Ruby 中,程序员可以利用各种技巧来提高代码的可读性和效率。本文将深入探讨 Ruby 中的常值,包括数值、符号、字符串和正则表达式。 1. 数值 - 整数:Ruby 支持两种整数类型——Fixnum 和 Bignum。Fixnum 用于...

    Ruby小例子(源代码)

    标题中的“Ruby小例子(源代码)”表明这是一个关于Ruby编程语言的学习资源,包含了多个示例源代码文件。Ruby是一种面向对象的、动态类型的编程语言,由Yukihiro Matsumoto(松本行弘)创建,它强调简洁性和可读性,...

    ruby ebook

    这本书,由Addison-Wesley出版,第二版于2006年10月发行,书名是"The Ruby Way",作者未在提供的信息中提及,但可以肯定的是,它深入浅出地介绍了Ruby语言的核心概念和实践技巧。 Ruby是一种面向对象的、动态类型的...

    Refactoring Ruby

    由于 Ruby 是一门灵活且强大的动态语言,因此书中还介绍了一些 Ruby 特有的重构技巧: - **利用元编程**:利用 Ruby 的元编程能力,如模块混合(mixins)、动态方法定义等特性进行重构。 - **利用动态类型**:通过...

    Ruby-TDD实战TestDrivenDevelopmentinAction

    通过一系列示例和练习,你将掌握TDD的核心技巧,并理解它如何提升软件开发的效率和质量。 总的来说,Ruby-TDD的实战经验能帮助开发者建立良好的编程习惯,提高代码质量,并推动项目的成功。无论你是Ruby新手还是...

    Everyday Scripting With Ruby

    - **实用技巧**:书中提供了大量的技巧和案例,帮助读者更高效地使用Ruby解决实际问题。 - **案例分析**:通过对具体案例的分析,可以深入了解Ruby在不同场景下的应用方式,如自动化测试、数据分析、网络爬虫等。 #...

    使用Python Lua和Ruby语言进行游戏编程

    "Premier.Press.Game.Programming.with.Python.Lua.and.Ruby.ebook-LiB.chm"很可能是一本关于使用这三种语言进行游戏编程的电子书,它可能会详细介绍如何利用这些语言来开发游戏,涵盖从基础概念到高级技巧的各种...

    The Ruby Programming Language

    - **Ruby Cookbooks**:提供了一系列实用的Ruby编程技巧和示例代码。 - **Learning Ruby**:适合Ruby初学者的基础教程。 - **Advanced Rails**:针对高级Ruby on Rails开发者的深入指南。 - **Rails Cookbook**:...

    Metaprogramming.Ruby

    ### Metaprogramming Ruby:掌握如专业人士般的编程技巧 #### 一、引言 《Metaprogramming Ruby: Programming Like the Ruby Pros》是一本深入探讨Ruby元编程技术的专业书籍,作者Paolo Perrotta通过丰富的实例和...

    生成PDF的ruby

    在Ruby编程语言中,生成PDF(Portable Document Format)文件是一项常见的任务,特别是在创建报告、发票、文档或任何需要打印或在线共享的静态...对于初学者,建议从官方文档和示例代码入手,逐步掌握PDF生成的技巧。

    ruby大纲资料.txt

    在Ruby实用技巧中,测试驱动开发(TDD)、测试框架、调试和性能分析工具、日志记录和错误处理等知识点也非常重要。Ruby的测试工具如RSpec和Minitest提供了编写单元测试和集成测试的框架,而byebug等调试工具帮助...

    ruby资源推荐.docx

    - **简介**:这是一个通过解决一系列小问题来学习Ruby的项目。每个问题都设计得非常巧妙,能够帮助学习者掌握Ruby的一个特定方面。 - **适合人群**:适合希望通过实践加深对Ruby理解的学习者。 2. **Exercism** ...

Global site tag (gtag.js) - Google Analytics