Module: IGem

Defined in:
lib/igem.rb

Overview

IGem - run gem executables with forking, thus save the loading time. Can be used to speed up Rails generate, Rails server startup or Rake from minutes to seconds.

Usage:

$ rails console
>> igem "script/something.rb", "argument1 argument2"
or
>> igem "rake db:migrate"
>> igem "rails server", wait: false
>> igem "rake -T", fork: false
>> Rails.server

You can use a simpler syntax:

IGem.rake "db:migrate"

You may not be able to change the Rails environment this way because bundler will not load gems from other envs

Defined Under Namespace

Modules: Rails, Rake

Class Method Summary collapse

Class Method Details

.method_missing(method_name, cmdline, opts = {}) ⇒ Object



25
26
27
# File 'lib/igem.rb', line 25

def method_missing method_name, cmdline, opts={}
  run "#{method_name} #{cmdline}", opts
end

.run(cmdline, opts = {}) ⇒ Object

Runs the specified command line with forking and loading the gem executable or ruby file.

executable can be a ruby file, a gem executable or a gem name and a gem executable like this: "rspec-core#rspec"

available.

fork: true    to fork the process or just run in this one (! rails generate and some others will stop the process after running)
wait: true    if fork is true, wait for the forked process with Process.wait
reload: true  call reload! if it exists
env: {}        update the environment with these values

Parameters:

  • cmdline

    The command line with the executable as the first word. The

  • opts (defaults to: {})

    a hash containing the options. The following options are



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/igem.rb', line 43

def run cmdline, opts={}
  opts = {
    :fork=>Process.respond_to?(:fork),
    :wait=>true,
    :env=>{},
    :reload=>true
  }.merge(opts)

  # split cmdline
  cmd, *args = cmdline.scan(/(?:[^"\s]+|"[^"]+")+/).map{|s|s.chars.grep(/[^"]/).join}

  # find executable
  case cmd
  when /\//
    # for example scripts/something.rb
    executable = cmd
  when /#/
    gem, cmd = *cmd.split("#")

    # for example rspec-core#rspec
    executable = Gem.bin_path(gem, cmd)
  else 
    # for example rspec
    executable = Gem.bin_path(nil, cmd)
  end


  # reload
  if opts[:reload]
    reload! if respond_to? :reload!
  end


  # if fork is requested
  if opts[:fork]
    fork do
      ENV.update opts[:env]
      ARGV.replace args
      load executable
    end

    # wait if requested
    Process.wait if opts[:wait]
  else
    # run without forking

    ENV.update opts[:env]
    ARGV.replace args
    load executable
  end

  if defined? ActiveRecord 
    ActiveRecord::Base.connection.execute("") rescue ActiveRecord::Base.connection.reconnect! 
  end 
  nil
end