I am using Nokogiri with open_uri to crawl web data in a Rails app. I have a NokogiriCrawler class:
class NokogiriCrawler
require 'open_uri'
def initialize
end
end
but always have this error: cannot load such file -- open_uri
Try this instead:
require 'open-uri'
P.S. This is unrelated to your actual problem, but requires should almost always go at the top of your file, not inside your class declaration.
Related
Still learning RoR, sometimes I'll see an example use of a library in plain Ruby that has require 'my_library'.
When we're in Ruby on Rails, are we able to do require? Or does everything have to be included in the gemfile (which I guess both installs and requires the library).
In particular I'm trying to call a API:
class MyModel < ActiveRecord::Base
has_many :other_models
def get_score
require 'rest_client'
response = RestClient.post 'https://sender.blockspring.com/api/blocks/da289f59df228ac4e89cebdfc9aa41fd?api_key=fe5cf0d86af27c086ab5cd4d0eab6641', { items_as_json_string: '[{"time_since_post_in_hours": 5, "upvote_count": 22}, {"time_since_post_in_hours": 3, "upvote_count": 502}]' }
end
end
You absolutely can require things, but you generally don't need to when they are declared in the Gemfile. One particular case where you'd need to require them is if you told it so, such as (in your Gemfile):
gem 'something_very_specific', require: false
Now, you'll need to require it in the "very specific" place you intended to use it.
require is part of Ruby and not unique to Rails. You can require stuff in Rails and it is normally done at the top of the Class and not inside of methods. require simply runs the file to make sure the functionality you are trying to use is loaded.
I need the Ruby module FileUtils to handle some operations with files.
I want to test that this require will work correctly in my controller. So I tried this in my console but got false as a result (this works fine when I'm not in a Rails console but just a plain Ruby console):
Go to the root directory of my project
$ rails c to open my console
> require 'fileutils' returns false.
What is the correct way to require a module via rails console? Why would this return false?
I'm assuming in my controller I can just do something like this, correct?
def create
require 'fileutils'
# my code that uses fileutils.
end
A false response from require means that the module is already loaded. You should be good to go without requiring this in your controller. See docs: http://www.ruby-doc.org/core-2.1.1/Kernel.html#method-i-require
It is most likely already required by default. Just type FileUtils in the console, it should respond
# => FileUtils
Returning false from require means that it's already loaded.
Try this from the console:
FileUtils.pwd
# => "/present/working/directory
I'm trying to fetch an image from Twitter:
open("http://api.twitter.com/1/users/profile_image/barackobama.png?size=bigger")
But I get:
RuntimeError: redirection forbidden: http://... -> https://...
There is an open issue and it seems that I can use an extension to open_uri but I don't know how it works. For example, if I place it in lib/ or if I paste the module in the console, it still doesn't work. Any idea?
I think the proper place to put such a patch is in a file inside config/initializers, i.e. config/initializers/open_uri_allow_unsafe_redirects_patch.rb. You have to require 'open-uri' before reopening the OpenURI module:
require 'open-uri'
module OpenURI
# the rest of the file here...
end
Then you have to call open passing the option allow_unsafe_redirects set to true:
open('http://api.twitter.com/1/users/profile_image/barackobama.png?size=bigger',
allow_unsafe_redirects: true)
You can find more informations about initializer files on the Ruby on Rails guide
I've just started using Ruby on Rails and so far it's working nicely. I'm now trying to implement a gem but it's not working, and I am hoping it's just a beginner mistake - something which I've not yet grasped!!
I've followed tutorials and got my hello world example - also managed to git push this to my Heroku account. I started to follow the tutorial here: http://railscasts.com/episodes/190-screen-scraping-with-nokogiri and got the following code working in Terminal (on mac)
require 'rubygems'
require 'nokogiri'
require 'open-uri'
url = "http://www.walmart.com/search/search-ng.do?search_constraint=0&ic=48_0&search_query=batman&Find.x=0&Find.y=0&Find=Find"
doc = Nokogiri::HTML(open(url))
puts doc.at_css("title").text
So that worked nicely. I can see the title inside of terminal. However, when I try to put this code in my view controller, it cannot find the nokogiri gem. The code in my controller is
class HomeController < ApplicationController
def index
require 'rubygems'
require 'nokogiri'
require 'open-uri'
url = "http://www.walmart.com/search/search-ng.do?search_constraint=0&ic=48_0&search_query=batman&Find.x=0&Find.y=0&Find=Find"
doc = Nokogiri::HTML(open(url))
#mattVar = doc.at_css("title").text
end
end
So then in my HTML, I have
<h1>Hello!</h1>
<p><%= #mattVar %></p>
Which should output the title as it does in the terminal window. However, I get an error saying no such file to load -- nokogiri
Any ideas where I'm going wrong?
If I do gem list I can see the nokogiri gem there.
UPDATE
I closed the local rails server and restarted. It's now working. Not sure if it was because of the work adding the gem to my root or doing the 'bundle install' (as the posts below suggested). Thanks for the help.
Firstly try changing your controller to be somthing like
class HomeController < ApplicationController
require 'nokogiri'
require 'open-uri'
def index
url = "http://www.walmart.com/search/search-ng.do?search_constraint=0&ic=48_0&search_query=batman&Find.x=0&Find.y=0&Find=Find"
doc = Nokogiri::HTML(open(url))
#mattVar = doc.at_css("title").text
end
end
I'm guessing you are also using bundler, check that you have include this gem and run bundle install.
You can find the documentation for this at http://gembundler.com/
You should put your various require statements outside of your index method. It won't slow you down much to have them in there, but you're asking Ruby to ensure that they are loaded every time the method is called. Better to just require them once at the top of your code. This won't cause your problem, however.
I suspect that you are testing your server under a different environment than what IRB is running in. Try removing the offending require statements for the moment and changing your HTML template to:
<h1>Environment</h1>
<ul>
<li>Ruby: <%=RUBY_VERSION%></li>
<li>Gems: <%=`gem list`%></li>
</ul>
I'm working on a Rails application. I have a Module called Animals. Inside this Module is a Class with the same name as one of my Models (Dog).
show_animal action:
def show_animal
require 'Animals/Bear.rb' #Works
require 'Animals/Dog.rb' #Fails
end
So the first require definitely works, the seconds fails.
MissingSourceFile (no such file to load -- Animals/Dog.rb):
I noticed that Dog.rb is the same file name as one of my models, is that what's causing this? I'm using Webrick.
Try using the full path:
require File.join(RAILS_ROOT, 'lib', 'Animals', 'Dog.rb')