ERB not wanting to render file in Rack App - ruby

When I use an erb method using:
require 'erb'
def erb(template)
path = File.expand_path("../views/#{template}", __FILE__)
ERB.new(File.read(path)).result(binding)
end
And afterward use a:
Rack::Response.new(erb('default.html.erb'))
It raises an Errno::ENOENT. Why is this? Thanks!

Looks like you may have gotten your file path wrong. Check to make sure that's right.

Related

Any way to do unqualified method calls?

If I have a script that looks like this:
require "FileUtils"
puts FileUtils.pwd()
is there anyway to do importing so that I don't have to write FileUtils? I want to just be able write pwd() instead of FileUtils.pwd().
require 'fileutils'
Object.include FileUtils
pwd
but never do it at home

Ruby: Can I 'require' a file which contains only a class?

I have a file /project/lib/invaccessor.rb with the following content
class InvAccessor
def initialize
#browser = "browser"
end
end
and a spec file project/spec/invaccessor_spec.rb which requires it
require_relative '../lib/invaccessor'
describe Invaccessor do
it {expect(2).to be_even}
end
When I run rspec spec/invaccessor.rb I get an uninitialized constant error for Invaccessor. Do I have to put all file contents in a module in order to access them?
I'm using Ruby 2.2.2.
Yes, you can.
Try this inside the directory where your classfile.rb lies:
>> require './classfile'
=> true
>> A
=> A
You definitely don't have to put a class into a module to require it.

Where to put helper functions for rake tasks and test files in Ruby on Rails?

In my Rails application I have a file sample_data.rb inside /lib/tasks as well as a bunch of test files inside my /spec directory.
All these files often share common functionality such as:
def random_address
[Faker::Address.street_address, Faker::Address.city].join("\n")
end
Where should I put those helper functions? Is there some sort of convention on this?
Thanks for any help!
You could create a static class, with static functions. That would look something like this:
class HelperFunctions
def self.random_address
[Faker::Address.street_address, Faker::Address.city].join("\n")
end
def self.otherFunction
end
end
Then, all you would need to do is:
include your helper class in the file you want to use
execute it like:
HelperFunctions::random_address(anyParametersYouMightHave)
When doing this, make sure you include any dependencies in your HelperFunctions class.
If you're sure it's rake only specific, you also can add in directly in RAILS_ROOT/Rakefile (that's probably not the case for the example you use).
I use this to simplify rake's invoke syntax :
#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
def invoke( task_name )
Rake::Task[ task_name ].invoke
end
MyApp::Application.load_tasks
That way, I can use invoke "my_namespace:my_task" in rake tasks instead of Rake::Task[ "my_namespace:my_task" ].invoke.
You share methods in a module, and you place such a module inside the lib folder.
Something like lib/fake_data.rb containing
module FakeData
def random_address
[Faker::Address.street_address, Faker::Address.city].join("\n")
end
module_function
end
and inside your rake task just require the module, and call FakeData.random_address.
But, if it is like a seed you need to do every time you run your tests, you should consider adding this to your general before all.
E.g. my spec_helper looks like this:
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
include SetupSupport
config.before(:all) do
load_db_seed
end
end
and the module SetupSupport is defined in spec/support/setup_support.rb and looks as follows:
module SetupSupport
def load_db_seed
load(File.join(Rails.root, 'db', 'seeds.rb'))
end
end
Not sure if you need to load the seeds, or are already doing this, but this is the ideal spot to also generate needed fake data.
Note that my setup support class is defined in spec/support because the code is only relevant to my specs, I have no rake task also needing the same code.

Why doesn't require add all names?

I have a file, my_helper.rb, that looks like this:
require 'cgi'
require 'enumerator'
module MyHelper
# ...
end
class MyUpstreamError < StandardError
# ...
end
When I require 'my_helper' elsewhere, MyHelper becomes visible, but MyUpstreamError does not. Why is this?
Ruby's require is analogous to include in C.
You might want to have a read though:
http://rubylearning.com/satishtalim/including_other_files_in_ruby.html
http://ionrails.com/2009/09/19/ruby_require-vs-load-vs-include-vs-extend/
It turned out to be a filename conflict. There was another file named my_helper.rb, which I had never edited, in a helpers directory in my Rails setup. It was shadowing this file, which was in lib.

Ruby koans triangle.rb require error

I'm doing the Ruby Koans tutorial, using notepad++.
The about_triangle_project.rb can't seem to load the triangle.rb file.
no such file to load -- triangle.rb <LoadError>
from <internal:lib/rubygems/custom_require>:29:in 'require'
from about_triangle_project.rb:4: in '<main>'
However I don't think I've altered the files. (I tried to fix it but always undid these when they didn't work)...
Here's the code in about_triangle_project.rb
require File.expand_path(File.dirname(__FILE__) + '/edgecase')
require 'triangle.rb' # this is line 4
class AboutTriangleProject < EdgeCase::Koan
def test_equilateral_triangles_have_equal_sides
assert_equal :equilateral, triangle(2, 2, 2)
assert_equal :equilateral, triangle(10, 10, 10)
end
(etc)
I have tried require 'triangle', that didn't work.
I tried using an absolute pathname, that didn't work.
and the triangle.rb file is in the same directory, unaltered, with comments and just this:
def triangle(a,b,c)
end
class TriangleError < StandardError
end
The triangle.rb file does exist in the same directory, so why can't it be found?
I hope I'm not missing something glaringly obvious!
It appears that on Windows, adding the current directory to the load path doesn't quite work right. Substituting require 'triangle.rb' for require_relative 'triangle.rb' should work, but is a bit of a hack. I don't use Windows, so I'm not sure what the proper solution would be.
I'd definitely look into obtaining a version of Sublime Text Editor, it makes things much cleaner and you can actually open folders in it.
And it looks like your pathing is wrong, I would say make sure that the address of triangle.rb is correct in your code.
Mine looks something more like this
require File.expand_path(File.dirname(FILE) + '/neo')
#You need to write the triangle method in the file 'triangle.rb'
require './triangle'
I'm learning ruby with the Koans right now and found this issue too.
So what was happening to us is that the current working directory (cwd) where the code is ran from affects ruby's require method. You will need to change where the cwd is to the folder of all the koans with cd .\.ruby\koans\ for example. Or, as Ben Langfeld answered, require_relative 'triangle' is a good and easy alternative.
For more info, I'd suggest checking out this What is the difference between require_relative and require in Ruby? thread. My takeaway from this was that require is better used for installed gems and libraries while require_relative is better for code written by you.

Resources