How can I require another .rb file in my rhtml file? - ruby

In my rhtml file, I want to require another ruby file in the same directory. So I tried:
<% require_relative 'another.rb' %>
but I got this error in my log:
(erb):2:in `require_relative': cannot infer basepath (LoadError)
Then I tried to use:
<% require './another.rb' %>
And it gives error saying:
/usr/local/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require': cannot load such file -- ./views/another.rb (LoadError)
Then I tried to see what is the base path by doing:
puts File.absolute_path(__FILE__)
And it returns:
(erb)
How can I require another file using relative path? I do not want to use absoulute path.

As you can see from the error, the current path is views (app/views). If the file you want is in your app's lib directory, you could do:
<% require_relative '../../lib/another' %>
You don't need .rb.
This is a fairly bad idea, though; you shouldn't be requiring things from inside views. If you're trying to access some sort of view-related functionality, you can require it in your controller; all controller actions are accessible to views. Going this route, it's best to wrap the functionality in a controller method.
You could also put the functionality into a helper; that's what helpers are for. See app/helpers/application_helper.rb for a good starting point, or make one specific to the view. See the view helper documentation.

A very unhealthy way is to add '.' to the load path
$LOAD_PATH << '.'
then you can use
<% require './another.rb' %>
The most usual way I believe that is
require File.join(File.dirname(__FILE__), 'path', 'to', '..', 'file')
If you consider that you are only using a constant and a relative path, I believe it is correct to say that this path is relative.

Related

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'

Using File::read in a provider's default.rb in Chef

I am trying to create an LWRP that will call the resource that is defined within itself. My cookbook's structure is as follows:
In the machine cookbook's provider, I have a code snippet as follows:
require 'chef/provisioning' # driver for creating machines
require '::File'
def get_environment_json
##environment_template = JSON.parse(File::read(new_resource.template_path + "environment.json"))
return ##environment_template
end
The code is only trying to read a json file and I am using File::read for it.
I keep getting an error as follows:
LoadError
cannot load such file -- ::File
Does anyone know how I can use File::read inside my LWRP's provider?
OK, so the prior two answers are both half right. You have two problems.
First, you can't require ::File as it's already part of Ruby. This is the cause of your error.
Second, if you call File.read you will grab Chef's File not ruby's. You need to do a ::File.read to use Ruby's File class.
require '::File'
Is incorrect and is causing the LoadError. Delete this line. You don't need it. File is part of the Ruby core and doesn't need to be required.
To further explain, the string argument to require represents the file name of the library you want to load. So, it should look like require "file", or require "rack/utils".
It happens becuase Chef already has a file resource. We have to use the Ruby File class in a recipe.We use ::File to use the Ruby File class to fix this issue. For example:
execute 'apt-get-update' do
command 'apt-get update'
ignore_failure true
only_if { apt_installed? }
not_if { ::File.exist?('/var/lib/apt/periodic/update-success-stamp') }
end
Source: https://docs.chef.io/ruby.html#ruby-class

Ruby including files

I have a Ruby app that runs on a server with no web interface. It is run using the command line(ruby path/to/file.rb).
I have classes in different files that I want to be accessible. The files are located in the "app/classes" directory.
I put this in the application.rb file:
config.autoload_paths += Dir["#{config.root}/classes"]
and I get an uninitialized constant error.
I can put in "require_relitive 'somefile'" but I would rather not have to do this for every class that is used. How do I create an autoload path and where should it be located at?
Use require_all
See https://github.com/jarmo/require_all
It basically allows you to write this:
require 'require_all'
require_all 'app/classes'
And all ruby files in app/classes will be loaded.

RSpec locating resource path

I have a little project (non Rails) and I'm using RSpec for testing. In order to load models I'm using:
require_relative "../lib/checkout"
However I'm encountering the problem with loading config files, for instance, the test no longer locates my "items.csv" when the following:
CSV.foreach("items.csv") do |row|
Note that the problem occurs only when spec is run from the spec directory, i.e:
rspec checkout_spec.rb
Running it from the project root is fine:
rspec spec/checkout_spec.rb
Any help would be appreciated.
CSV.foreach uses the current directory to find the file. You should probably use File.expand_path to get to an absolute path to items.csv to avoid this problem.
Edited to add an example
Assuming that the file is at root/items.csv, and the ruby file with this code is at root/lib/file.rb, you could write
path = File.expand_path File.join(File.dirname(__FILE__), '..', 'items.csv')
CSV.foreach path do |row|
# rest of code...

How do I require a file from inside a directory with Ruby?

I think I'm missing something here. I have a directory like this:
myapp
|-lib
|-package1
|-dostuff.rb
|-package2
|-dostuff.rb
From an irb console I'm trying to test the library before I add it to my real project (a Rails app). However, typing this:
require 'lib/package1/dostuff'
returns an error saying it can't find the file to load. I added the lib directory to the load path but I'm not able to load the file.
What am I forgetting? The two filenames don't have to be the same but that's how they are to begin with (they are auto-generated from some web services I need to call using soap4r; each package represents a different web service API group)
If the directory "lib" is in the load path, the argument to require must be relative to lib. So require 'package1/dostuff' without the lib, otherwise it will look for lib/lib/package1/dostuff.rb.
In Ruby 1.9 there's the new require_relative method, which would let you do require_relative "../package2/dostuff" from within package1/dostuff.rb.

Resources