How to Get a List of Files That Have Been 'Required' in Ruby

How do I get a list of files that have been `required` in Ruby?

You can't do this exactly, because requiring one file may require others, and Ruby can't tell the difference between the file that you required and the file that someone else required.

You can check out $LOADED_FEATURES for a list of every single thing that's been required. But you should use Bundler if you want to specify dependencies explicitly.

Here's a thoroughly imperfect way to guess at the gem names and enumerate everything:

ruby-1.9.2-p180 :001 > $LOADED_FEATURES.
select { |feature| feature.include? 'gems' }.
map { |feature| File.dirname(feature) }.
map { |feature| feature.split('/').last }.
uniq.sort
=> ["1.9.1", "action_dispatch", "action_pack", "action_view", "actions", "active_model", "active_record", "active_support", "addressable", "agent", "array", "aws", "builder", "bundler", "cache_stores", "cancan", "cdn", "class", "client", "common", "compute", "connection", "control", "controllers", "core", "core_ext", "core_extensions", "css", "data_mapper", "decorators", "dependencies", "dependency_detection", "deprecation", "devise", "digest", "dns", "encodings", "encryptor", "engine", "errors", "excon", "ext", "failure", "faraday", "fields", "fog", "formatador", "geographer", "haml", "hash", "helpers", "heroku_san", "hmac", "hooks", "hoptoad_notifier", "html", "http", "i18n", "idna", "importers", "inflector", "initializers", "instrumentation", "integrations", "interpolate", "interval_skip_list", "jquery-rails", "json", "kaminari", "kernel", "lib", "mail", "metric_parser", "mime", "mixins", "model_adapters", "models", "module", "mongo_mapper", "mongoid", "multibyte", "new_relic", "node", "nokogiri", "numeric", "oauth", "object", "omniauth", "orm_adapter", "package", "parser", "parsers", "plugin", "pp", "providers", "queued", "rack", "rails", "railtie", "redis", "request", "request_proxy", "resp ruby-1.9.2-p180 :008 >onse", "resque", "retriever_methods", "routing", "ruby_extensions", "ruby_flipper", "rubygems", "runtime", "samplers", "sass", "sax", "script", "scss", "selector", "sequel", "ses", "shell", "signature", "simple_geo", "state_machine", "stats_engine", "storage", "strategies", "string", "tar_reader", "template", "terremark", "thor", "tokens", "tree", "treetop", "twitter", "us", "util", "vendor", "version_specific", "visitors", "warden", "xml", "xml_mini", "xpath", "xslt"]

Get names of all files from a folder with Ruby

You also have the shortcut option of

Dir["/path/to/search/*"]

and if you want to find all Ruby files in any folder or sub-folder:

Dir["/path/to/search/**/*.rb"]

How does Ruby know where to find a required file?

When you start your rails app it runs config/boot.rb which calls Rails::Initializer.set_load_path and thatsets up the $LOAD_PATH.

Ruby uses that list of directories to find the files specified on a require line. If you give it an absolute path like require '/home/lolindrath/ruby/lib.rb' it will skip that search.

This is roughly analogous to #include <stdlib.h> in C/C++ where it searches the include path you give the compiler to find that header file.

How to test obtaining a list of files within a directory using RSpec?

I don't think you need to test the library, but if you have a method like

def file_names
files = []
Find.find(Dir.pwd){|file| files << file}
........
end

you can stub the find method to return a list of files like so

it "should return a list of files within the specified directory" do
Find.stub!(:find).and_return(['file1', 'file2'])
@object.file_names
end

or if you want to set the expectation then you can do

it "should return a list of files within the specified directory" do
Find.should_receive(:find).and_return(['file1', 'file2'])
@object.file_names
end

Getting the full path for a required file

You can look for loaded files in $LOAD_PATH aka $: variable as described in Show full path name of the ruby file when it get loaded. And you can list required files by querying $LOADED_FEATURES aka $"

require '/home/ashish/samples/required_test.rb'

$".each do |path|
puts path
end

More info on require - http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-require

How do I read all the file names of a directory into an array?

You can use this:

files = Dir.foreach(dir).select { |x| File.file?("#{dir}/#{x}") }

This returns the filenames, i.e. without folder.

If you need the complete path, use something like this:

files = Dir.foreach(dir) \
.map { |x| File.expand_path("#{dir}/#{x}") } \
.select { |x| File.file?(x) }

How to get all the filenames of the files inside a folder in Ruby

Use Dir::glob method as below

Dir.glob("#{path}/*.yml").each_with_object({}) do |filename,hsh|
hsh[File.basename(filename,'.yml')] = filename
end

How to list files on the server with Ruby Rails?

It is quite simple. In your controller:

def index
@files = Dir["/path/to/dir/*.txt"] #Array with files full_names
end

In your view:

<ul>
<% @files.each do |file| %>
<li><%=file%></li>
<% end %>
</ul>


Related Topics



Leave a reply



Submit