31 05 2008

irbrc i railsrc

Wyprodukowano na podstawie materiałów znalezionych w sieci.

Linki na końcu wpisu.


.irbrc

# vim: ft=ruby
IRB_START_TIME = Time.now
print "Loading... "
ARGV.concat [ "--readline", "--prompt-mode", "simple" ]

require 'rubygems'
require 'pp'
require 'irb/completion'
require 'irb/ext/save-history'

# require ...
%w(
  wirble 
  map_by_method 
  what_methods
  duration
).each do |gem|
    begin 
        require gem
    rescue LoadError
        puts "Error loading #{gem}. Run 'sudo gem install #{gem}'"
    end
end

IRB.conf[:SAVE_HISTORY] = 1000
IRB.conf[:AUTO_INDENT] = true
IRB.conf[:USE_READLINE] = true
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"
IRB.conf[:PROMPT_MODE] = :SIMPLE

if Object.const_defined?(:Wirble)
    Wirble.init(:debug => true)
    Wirble.colorize
end

# object.local_methods
class Object 
    def local_methods(obj = self)
        obj.methods(false).sort
    end
end

# method finder
class Object
  def what?(*a)
    MethodFinder.new(self, *a) unless $in_method_find
  end
  def megaClone
    begin self.clone; rescue; self; end
  end
end
class MethodFinder
  def initialize( obj, *args )
    @obj = obj
    @args = args
  end
  def ==( val )
    MethodFinder.show( @obj, val, *@args )
  end

  # Find all methods on [anObject] which, when called with [args] return [expectedResult]
  def self.find( anObject, expectedResult, *args, &block )
    $in_method_find = true
    eval 'class DummyOut; def write(*args); end; end;'
    stdout, stderr = $stdout, $stderr
    $stdout = $stderr = DummyOut.new
    # change this back to == if you become worried about speed or something
    res = anObject.methods.select { |name| anObject.method(name).arity <= args.size }.
             select { |name| begin anObject.megaClone.method( name ).call( *args, &block ) == expectedResult; 
                             rescue Object; end }
    $stdout, $stderr = stdout, stderr
    $in_method_find = false
    res
  end

  # Pretty-prints the results of the previous method
  def self.show( anObject, expectedResult, *args, &block)
    find( anObject, expectedResult, *args, &block).each { |name|
      print "#{anObject.inspect}.#{name}" 
      print "(" + args.map { |o| o.inspect }.join(", ") + ")" unless args.empty?
      puts " == #{expectedResult.inspect}" 
    }
  end
end

# show_regexp - stolen from the pickaxe
def show_regexp(a, re)
   if a =~ re
      "#{$`}<<#{$&}>>#{$'}"
   else
      "no match"
   end
end
# Convenience method on Regexp so you can do
# /an/.show_match("banana")
class Regexp
    def show_match(a)
        show_regexp(a, self)
    end
end
require 'irb_callbacks'
require 'benchmark'
module IRB
    def self.around_eval(&block)
        @timing = Benchmark.realtime do
            block.call
        end
    end

    def self.after_output
        if @timing > 1
            puts "=> #{'%.3f' % @timing} seconds :("
        end
    end
end

# duration
at_exit { puts Duration.new(Time.now - IRB_START_TIME) }

puts "OK"
load File.dirname(__FILE__) + '/.railsrc' if $0 == 'irb' && ENV['RAILS_ENV']
.railrc
print "Loading railsrc..."
# vim: ft=ruby

require 'logger'
# require 'activesupport'
Object.const_set(:RAILS_DEFAULT_LOGGER, Logger.new(STDOUT))

def sql(query)
  pp(ActiveRecord::Base.connection.select_all(query))
end

def define_model_find_shortcuts
  model_files = Dir.glob("app/models/**/*.rb" )
  table_names = model_files.map { |f| File.basename(f).split('.' )[0..-2].join }
  table_names.each do |table_name|
    Object.instance_eval do
      define_method(table_name) do |*args|
        table_name.camelize.constantize.send(:find, *args)
      end
    end
  end
end
IRB.conf[:IRB_RC] = Proc.new { define_model_find_shortcuts }

rails_root = File.basename(Dir.pwd)
IRB.conf[:PROMPT] ||= {}
IRB.conf[:PROMPT][:RAILS] = {
    :PROMPT_I => "#{rails_root}> ",
    :PROMPT_S => "#{rails_root}* ",
    :PROMPT_C => "#{rails_root}? ",
    :RETURN   => "=> %s\n" 
}
IRB.conf[:PROMPT_MODE] = :RAILS

puts "OK"

Prezentacja oręża:

$ irb
Loading... OK
>> # *dopelnianie nazw metod tabem*
>> p<tab><tab>
p                                pretty_print_cycle               protected_methods
po                               pretty_print_inspect             public
poc                              pretty_print_instance_variables  public_methods
popb                             print                            pushb
popws                            printf                           pushws
pp                               private                          putc
pretty_inspect                   private_methods                  puts
pretty_print                     proc                             pwws
>> # wypas

>> h = { :foo => 1, :bar => 2, :dupa => false }
=> {:bar=>2, :foo=>1, :dupa=>false}  # <--- dzieki Wirble to jest w kolorze, ale tutaj tego nie widac :)
>> class Ble
>>   def b
>>     end
>>   end
=> nil # IRB.conf[:AUTO_INDENT] = true

# method finder! morowo! :)
>> "oki".what? == "OKI" 
"oki".swapcase == "OKI" 
"oki".swapcase! == "OKI" 
"oki".upcase == "OKI" 
"oki".upcase! == "OKI" 
=> ["swapcase", "swapcase!", "upcase", "upcase!"]

# show_regexp
>> show_regexp("foo bar test", /\w+est/)
=> "foo bar <<test>>" 

# mozna tez tak
>> /(s.\w+)/.show_match("foo bar s_test")
=> "foo bar <<s_test>>" 
>> /(s.\w+)/.show_match("nie ma")
=> "no match" 

# irb_callbacks, zabawka ^^
>> 2.times { sleep 0.52 }
=> 2
=> 1.040 seconds :(

# duration
>> quit
12 minutes and 47 seconds

# czas na railsy
$ ./script/console 
Loading development environment (Rails 2.0.2)
Loading... OK
Loading railsrc...OK
linuxlinki> Link.count
  SQL (0.000222)   SET SQL_AUTO_IS_NULL=0
  Link Columns (0.041859)   SHOW FIELDS FROM `links`
  SQL (0.000514)   SELECT count(*) AS count_all FROM `links` 
=> 207

linuxlinki> sql "show tables" 
  SQL (0.010506)   show tables
[{"Tables_in_linuxlinki"=>"authors"},
 {"Tables_in_linuxlinki"=>"categories"},
 {"Tables_in_linuxlinki"=>"links"},
 {"Tables_in_linuxlinki"=>"rates"},
 {"Tables_in_linuxlinki"=>"redirects"},
 {"Tables_in_linuxlinki"=>"rss"},
 {"Tables_in_linuxlinki"=>"schema_info"},
 {"Tables_in_linuxlinki"=>"sessions"},
 {"Tables_in_linuxlinki"=>"taggings"},
 {"Tables_in_linuxlinki"=>"tags"}]
=> nil

linuxlinki> link(:first)
  Link Load (0.000453)   SELECT * FROM `links` LIMIT 1
...
linuxlinki> 

Strony z których korzystałem przy tworzeniu plików konfiguracyjnych:

http://errtheblog.com/posts/24-irb-mix-tape

http://poignantguide.net/ruby/expansion-pak-1.html

http://radarek.jogger.pl/2007/05/28/interaktywny-ruby/

http://utilitybelt.rubyforge.org/

http://zargony.com/2008/04/28/five-tips-for-developing-rails-applications

http://www.sufixo.com/raw/index.php/2006/05/29/tip_ruby_irb_auto-complete/

http://drnicwilliams.com/2006/10/12/my-irbrc-for-consoleirb/

http://snippets.dzone.com/posts/show/2586

http://dotfiles.org/%7Elattice/.irbrc

http://dotfiles.org/~topfunky/.irbrc

http://quotedprintable.com/2007/9/13/my-irbrc

http://blog.nicksieger.com/articles/2006/05/30/irbrc-on-windows

http://ruby.tie-rack.org/3/my-irbrc/

http://blog.nicksieger.com/articles/2006/04/23/tweaking-irb

http://www.ruby-forum.com/topic/84414#new

http://redhanded.hobix.com/inspect/stickItInYourIrbrcMethodfinder.html

http://nikolasco.livejournal.com/339449.html

http://redhanded.hobix.com/inspect/stickItInYourIrbrcMethodfinder.html

http://programmingishard.com/

http://ozmm.org/posts/railsrc.html

http://weblog.jamisbuck.org/2007/2/1/per-developer-configuration

http://snipplr.com/view/5135/my-railsrc/


* - Pola wymagane


simple_captcha.jpg (*)