简体   繁体   中英

Permanently add a directory to Ruby $LOAD_PATH

I'd like the option to use awesome_print in every IRB console or Rails console.

The IRB console is pretty much working satisfactorily right now. If I run irb , I can type require 'awesome_print' and it works.

The Rails console isn't as easy. require 'awesome_print' doesn't work. I apparently have to do this:

> $LOAD_PATH << '~/.rvm/gems/ruby-2.1.8/gems/awesome_print-1.7.0/lib'

After that, require 'awesome_print' works fine.

But I definitely don't want to have to type $LOAD_PATH << '~/.rvm/gems/ruby-2.1.8/gems/awesome_print-1.7.0/lib' and then require 'awesome_print' every single time I open a Rails console just to be able to use awesome_print . That seems ridiculous.

So, how can I permanently add a path to Ruby's $LOAD_PATH ?

Note: I don't want to add awesome_print to the Gemfile of any particular project. I want awesome_print to be available to all my Ruby/Rails projects.

You could simply use aa ~/.irbrc file and do:

require 'awesome_print'

Now, open up another IRB prompt:

irb(main):003:0> ap hash
{
    "a" => "b"
}

Edit: this isn't working in rails, seems to be a known issue .

puts the following to the .irbrc :

to_load = %w[
  awesome_print
  coderay
  hirb
  pry
  pry-doc
  pry-remote
  pry-theme
  slop
  yard
].join('|')

regexp = Regexp.new( "(#{to_load})" )

Gem.path.each do |path|
  Dir.new("#{path}/gems").each do |gem_path|
    next if %w[ . .. ].any?{ |d| gem_path == d }

    new_el = "#{path}/gems/#{gem_path}/lib"
    $LOAD_PATH << new_el if new_el =~ regexp
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM