Ruby 'require' unable to load such a file - ruby

I want to require file all_class from file log_in_test.rb.
I tried all kinds of require and require_relative, for example
#require "../../ib4b-template/features/page-object/all_class"
require_relative "page-object/all_class"
and they are not working. Can anyone kindly give me a hand?

Try this:
require_relative 'all_class' # without 'page-object/'
The most common way to solve this problem is using File.dirname(__FILE__):
require File.join(File.dirname(__FILE__), '..', 'all_class')

Use
require_relative '../page_object/all_class'
relative to support/log_in_test.rb, all_class.rb lies in above path.
require doesn't find if the directory structure is not in the Ruby's library path.

require_relative './page_object/all_class.rb'
or
require_relative './page_object/all_class'
the '.rb' part is optional
You should use require_relative instead of require when you are working on a project and want to require one file from one of the directories into another.
You should use require to add gem libraries to your project.
Also, a good practice to use when working on a larger practice is to make a environment.rb file in the config folder and have that require all the the models and then having the executables requiring that environment file.

require File.join(File.dirname(__FILE__), '..', '..','page-object', 'all_class')

Related

How to fix "`require_relative': cannot load such file" cannot load - Ruby

Tried to solve this on my own and so far no luck...
Error below:
1: from bin/run:3:in `<main>'
bin/run:3:in `require_relative': cannot load such file -- /Users/jason/Development/code/First Project/bin/bin/environment.rb (LoadError)
What's in my bin folder:
#!/usr/bin/env ruby
require_relative './bin/environment.rb'
CLI.new.call
In my config folder:
require 'pry'
require 'httparty'
require_relative "./lib/api.rb"
require_relative "./lib/cli.rb"
require_relative "./lib/pokemon.rb"
Project Directory:
-->Firstproject
->bin
-run
->config
-environment.rb
->lib
-api.rb
-cli.rb
-pokemon.rb
-gitignore
-Gemfile
-README.md
I think you just need to adjust the path to correctly reference your environment.rb source file:
#!/usr/bin/env ruby
require_relative '../config/environment.rb'
CLI.new.call
If you look closely where your environment.rb file lives, it is in the project_dir/config/environment.rb but your bin/run you are attempting to locate the file at ./bin/environment.rb which doesn't exist according to your Project Directory layout.
Check that your environment.rb file lives in config folder, not in lib. So change it to
require_relative './config/environment.rb'

Problems with requiring files inside gem [duplicate]

What is the difference between require_relative and require in Ruby?
Just look at the docs:
require_relative complements the builtin method require by allowing you to load a file that is relative to the file containing the require_relative statement.
For example, if you have unit test classes in the "test" directory, and data for them under the test "test/data" directory, then you might use a line like this in a test case:
require_relative "data/customer_data_1"
require_relative is a convenient subset of require
require_relative('path')
equals:
require(File.expand_path('path', File.dirname(__FILE__)))
if __FILE__ is defined, or it raises LoadError otherwise.
This implies that:
require_relative 'a' and require_relative './a' require relative to the current file (__FILE__).
This is what you want to use when requiring inside your library, since you don't want the result to depend on the current directory of the caller.
eval('require_relative("a.rb")') raises LoadError because __FILE__ is not defined inside eval.
This is why you can't use require_relative in RSpec tests, which get evaled.
The following operations are only possible with require:
require './a.rb' requires relative to the current directory
require 'a.rb' uses the search path ($LOAD_PATH) to require. It does not find files relative to current directory or path.
This is not possible with require_relative because the docs say that path search only happens when "the filename does not resolve to an absolute path" (i.e. starts with / or ./ or ../), which is always the case for File.expand_path.
The following operation is possible with both, but you will want to use require as it is shorter and more efficient:
require '/a.rb' and require_relative '/a.rb' both require the absolute path.
Reading the source
When the docs are not clear, I recommend that you take a look at the sources (toggle source in the docs). In some cases, it helps to understand what is going on.
require:
VALUE rb_f_require(VALUE obj, VALUE fname) {
return rb_require_safe(fname, rb_safe_level());
}
require_relative:
VALUE rb_f_require_relative(VALUE obj, VALUE fname) {
VALUE base = rb_current_realfilepath();
if (NIL_P(base)) {
rb_loaderror("cannot infer basepath");
}
base = rb_file_dirname(base);
return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
}
This allows us to conclude that
require_relative('path')
is the same as:
require(File.expand_path('path', File.dirname(__FILE__)))
because:
rb_file_absolute_path =~ File.expand_path
rb_file_dirname1 =~ File.dirname
rb_current_realfilepath =~ __FILE__
Summary
Use require for installed gems
Use require_relative for local files
require uses your $LOAD_PATH to find the files.
require_relative uses the current location of the file using the statement
require
Require relies on you having installed (e.g. gem install [package]) a package somewhere on your system for that functionality.
When using require you can use the "./" format for a file in the current directory, e.g. require "./my_file" but that is not a common or recommended practice and you should use require_relative instead.
require_relative
This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use
require_relative '../../../filename'
(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).
Note that require_relative uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative path "stable" as it always be relative to the file requiring it in the same way.
From Ruby API:
require_relative complements the
builtin method require by allowing you
to load a file that is relative to the
file containing the require_relative
statement.
When you use require to load a file,
you are usually accessing
functionality that has been properly
installed, and made accessible, in
your system. require does not offer a
good solution for loading files within
the project’s code. This may be useful
during a development phase, for
accessing test data, or even for
accessing files that are "locked" away
inside a project, not intended for
outside use.
For example, if you have unit test
classes in the "test" directory, and
data for them under the test
"test/data" directory, then you might
use a line like this in a test case:
require_relative "data/customer_data_1"
Since neither
"test" nor "test/data" are likely to
be in Ruby’s library path (and for
good reason), a normal require won’t
find them. require_relative is a good
solution for this particular problem.
You may include or omit the extension
(.rb or .so) of the file you are
loading.
path must respond to to_str.
You can find the documentation at http://extensions.rubyforge.org/rdoc/classes/Kernel.html
The top answers are correct, but deeply technical. For those newer to Ruby:
require_relative will most likely be used to bring in code from another file that you wrote.
for example, what if you have data in ~/my-project/data.rb and you want to include that in ~/my-project/solution.rb? in solution.rb you would add require_relative 'data'.
it is important to note these files do not need to be in the same directory. require_relative '../../folder1/folder2/data' is also valid.
require will most likely be used to bring in code from a library someone else wrote.
for example, what if you want to use one of the helper functions provided in the active_support library? you'll need to install the gem with gem install activesupport and then in the file require 'active_support'.
require 'active_support/all'
"FooBar".underscore
Said differently--
require_relative requires a file specifically pointed to relative to the file that calls it.
require requires a file included in the $LOAD_PATH.
I just saw the RSpec's code has some comment on require_relative being O(1) constant and require being O(N) linear. So probably the difference is that require_relative is the preferred one than require.
I want to add that when using Windows you can use require './1.rb' if the script is run local or from a mapped network drive but when run from an UNC \\servername\sharename\folder path you need to use require_relative './1.rb'.
I don't mingle in the discussion which to use for other reasons.
absolute path
require './app/example_file.rb'
shortened name
require_relative 'example_file'

Avoiding dependency load order

I am writing a gem that looks as such:
lib/my_gem.rb:
require 'base64'
require 'ostruct'
require 'my_gem/utils.rb'
require 'my_gem/base.rb'
...
This has been fine until recently when the gem has added more functionality and the lib/my_gem directory has grown and grown.
Now, I'm having to be really careful to require my classes and modules in a very specific order because something in utils requires that base.rb be loaded first. However, something in base.rb requires that app.rb be loaded before that.
So it turns into:
# require all standard libraries first
require 'base64'
require 'ostruct'
require 'my_gem/app.rb' # be sure this is loaded before base!
require 'my_gem/base.rb' # be sure this is loaded before utils!
require 'my_gem/utils.rb' # be sure this is loaded before some other class!
I end up having a mess in this file all due to order of dependencies and I feel like there has to be a better way?
Try using Kernel#autoload:
require 'base64'
require 'ostruct'
autoload :SomeModule, 'my_gem/app.rb'
autoload :AnotherModule, 'my_gem/base.rb'
autoload :SomeClass, 'my_gem/utils.rb'
The idea is that the source file is not loaded until the module/class defined in it is used, therefore you don't need to take care of the order of requiring source files.

How to require file from `gem` which are not under `lib` directory?

I want to write spec for my rubocop custom cop. This gem has handy helpers defined here. I want to require it. How to achieve what?
I've tried to use Gem.find_files, and this gives me ability to require any file in that gem, but only under lib directory.
For example:
# this requires ...gems/rubocop-0.29.1/lib/rubocop/formatter/formatter_set.rb
require Gem.find_files('rubocop/formatter/formatter_set.rb').first
# but I need ...gems/rubocop-0.29.1/spec/support/cop_helper.rb
The following describes why I need it. I have spec/rubocop/my_custom_cop_spec.rb
require 'spec_helper'
require ? # What I should I write?
RSpec.describe RuboCop::Cop::Style::MyCustomCop do
it 'some test' do
inspect_source(cop, 'method(arg1, arg2)') # This helper I want to use from rubocop spec helpers
end
end
When I try plain require:
require 'rubocop/spec/support/cop_helper'
I receive error:
/home/user/.gem/ruby/2.0.0/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:274
:in `require': cannot load such file -- rubocop/spec/support/cop_helper
I found a solution that I think is a little more syntactically elegant:
gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"
I was so blinded, I already have path to file and able to get relative from it.
require 'pathname'
rubocop_path = Pathname.new(Gem.find_files('rubocop.rb').first).dirname
rubocop_path # => ...gems/rubocop-0.29.1/lib
require "#{rubocop_path}/../spec/support/cop_helper.rb"

Environment configuration for Sinatra error

I have an environment config file at config/environment.rb with the following:
require 'rubygems'
require 'bundler'
Bundler.setup
require 'sinatra'
require 'sinatra/base'
require 'sinatra/reloader'
and in my config.ru I have:
require File.expand_path('../config/environment', __FILE__)
require 'slim'
require 'coffee-script'
require 'padrino-helpers'
require 'sinatra/twitter-bootstrap'
I am getting the error :
Errno::ENOENT at /profile
No such file or directory - /Users/myusername/projects/accounts/config/views/profile.slim
and this only goes away when I remove require 'sinatra' from the config/environment.rb file and into config.ru. Can anyone explain why this happens? I assumed that the require File.expand_path('../config/environment', __FILE__) will simply include all requires from that file into config.ru but that doesn't seem to be the case. It now thinks my views live inside the config folder.
I followed the suggestion given here: How do I make Rake tasks run under my Sinantra app/environment? but again, moving require 'sinatra' into the environment breaks the app.
The error looks like it is from Sinatra being unable to find a Slim template when rendering a response, because it’s looking for a views directory under the config directory. By default Sinatra looks for the views dir relative to the application file, which (again by default) is the file that calls require 'sinatra'. In your case the require line is in config/environment.rb so Sinatra treats that as the app file and looks for the views dir below it.
I’m assuming you have an actual application file that you haven’t shown. The simplest solution is probably to explicitly set the application file setting in there:
set :app_file, __FILE__
Depending on your setup you might want to specify the view directory directly instead:
set :views, 'path/to/views'

Resources