Routing error "uninitialized constant Info" - ruby-on-rails

I have a module in /lib
Module Info
class Inf
def getNum
num = Array.new
num.push(2,1)
end
end
In the controller informations_controller I have 'require Info' and the follow code:
def index
#informations = Info::Inf.getNum().num
respond_to do |format|
format.html # index.html.erb
format.json { render json: #informations }
end
end
But it always gives the error
Routing Error
uninitialized constant Info
Since the router I have defined "root :to => 'informations#index'" what could be missing?

it should be module not Module and also you should name file info.rb and also you should be sure lib is in auto_load paths inconfig/application.rb
config.autoload_paths += %W(#{config.root}/lib)
so it should be something like this lib/info.rb:
module Info
class Inf
...
end
end

Related

rails root_url redirects me to www.example.com

I'm getting something really weird when I execute my tests with rails test.
I'm trying to understand and create my first controller tests and I get something unexpected.
I get this error in the console:
F
Failure:
FeedbacksControllerTest#test_should_create_resource [/Users/Daniel/GitHub/haeapua-rails/test/controllers/feedbacks_controller_test.rb:15]:
Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/>
Response body: <html><body>You are being redirected.</body></html>
here is my test
test "should create resource" do
assert_difference 'Feedback.count', 1 do
post feedbacks_url, params: { feedback: { email: "me#myemail.com", summary: "my feedback", rating: 5 } }
end
assert_response :success
assert_redirected_to root_url
end
here is my controller
class FeedbacksController < ApplicationController
# GET /feedbacks/new
def new
#feedback = Feedback.new
# #feedback.user = current_user if user_signed_in?
end
# POST /feedbacks
def create
#feedback = Feedback.new(feedback_params)
# #feedback.user = current_user if user_signed_in?
if #feedback.save
# flash[:info] = "We got it, thanks. Someone will contact you ASAP once we read it"
redirect_to root_url
else
render :new
end
end
private
def feedback_params
params.require(:feedback).permit(:email, :summary, :rating)
end
end
When I put a "puts root_url" in my feedback controller just before the redirect_to I get the value "http://www.example.com/". I search for root_url in my whole code and the only part I have it is in the Controller and in my routes root to: 'static_pages#concept'
I'm using devise, do you think it could be because of that? I'm a bit lost and don't know where to start looking!
It's a weird quirk but rails has two types of url_helpers for routes. something_url and something_path. The first is an absolute path, http://www.awesome.com/something) the second is the relative path (/someurl).
Unless you have a domain name set explicitly on your test environment, use the _path helpers in your tests. If you want to use the _url helpers then you need to configure a base url in your application's test environment (config/environments/test.rb)
Maybe some default config is setting this value. https://github.com/teamcapybara/capybara/blob/master/lib/capybara.rb#L452
Capybara.configure do |config|
# ...
config.default_host = "http://www.example.com"
# ...
end
You have to override this setting in your project config.
If it's not capybara it could be rails issue ? From the input of this thread https://github.com/rspec/rspec-rails/issues/1275 I would try something like this
# config/environment/test.rb
config.action_controller.default_url_options = {
host: '0.0.0.0:3000' # or whatever your host is
}
In the thread I found:
# putting this into initializer of test framework
[ApplicationController, ActionController::Base].each do |klass|
klass.class_eval do
def default_url_options(options = {})
{ :host => "example.com" }.merge(options) # or localhost:8888 or 0.0.0.0:3000 or whatever your server is
end
end
end

Work with default routes but custom routes give uninitialized constant Api::V1::UserController

I know this questions is asked several times but I checked those answers but nothing seems to fix my issue.
users_controller.rb on path app/controllers/api/v1/
module Api
module V1
class UsersController < ApplicationController
def create_user
#users = User.new(user_params)
if #users.save
render json: { status: '201', message: 'User created successfully' }
else
render json: { status: '400', message: 'Invalid user info', data: #users.errors }
end
end
def user_params
params.permit(:first_name, :last_name, :email, :password)
end
end
end
end
routes.rb
namespace 'api' do
namespace 'v1' do
post "user/createuser", to: "user#create_user"
end
end
What I have tried:
Checked the directory structure it is as mentioned
Restarted the server and checked
Folder name: all simple controllers > api > v1
But this works fine when I changed the routes.rb
post "user/createuser", to: "user#create_user"
to resource :users
and
def create_user
to def create
Why things does not work when I define custom routes instead of using default routes? How to get this work with custom routes
Due to Rails conventions I believe you need to update your route with
post "user/createuser", to: "users#create"
instead of
post "user/createuser", to: "user#create_user"

Running into "uninitialized constant" with whenever gem

Trying to use whenever gem today. Running into this error uninitialized constant EntriesController::RedditScrapper ... how do I fix this?
Current Controller
class EntriesController < ApplicationController
def index
#entries = Entry.all
end
def scrape
RedditScrapper.scrape
respond_to do |format|
format.html { redirect_to entries_url, notice: 'Entries were successfully scraped.' }
format.json { entriesArray.to_json }
end
end
end
lib/reddit_scrapper.rb
require 'open-uri'
module RedditScrapper
def self.scrape
doc = Nokogiri::HTML(open("https://www.reddit.com/"))
entries = doc.css('.entry')
entriesArray = []
entries.each do |entry|
title = entry.css('p.title > a').text
link = entry.css('p.title > a')[0]['href']
entriesArray << Entry.new({ title: title, link: link })
end
if entriesArray.map(&:valid?)
entriesArray.map(&:save!)
end
end
end
config/schedule.rb
RAILS_ROOT = File.expand_path(File.dirname(__FILE__) + '/')
every 2.minutes do
runner "RedditScrapper.scrape", :environment => "development"
end
Please help me to figure out the right runner task to write in ...
Application.rb
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module ScrapeModel
class Application < Rails::Application
config.autoload_paths << Rails.root.join('lib')
end
end
Rails doesn't auto load the lib folder. You need to add the following line to your config/application.rb:
config.autoload_paths << Rails.root.join('lib')
From what I can tell, you've defined RedditScrapper as a module, but you are trying to use it as a class... (ie calling a method on it).
You can either: turn it into a class (just change module to class) OR define all relevant methods as module_functions
The former is probably preferable given your chosen usage.

UrlGenerationError: No route matches, missing required keys and link_to

I'm having issues with my static pages strategy on rails.
I have a controller that handles static pages. Basically, it reads templates in the app/views/static directory and render as asked. Like so:
class StaticController < ApplicationController
def show
templ = File.join(params[:controller], params[:page])
puts params, templ
render templ
rescue ActionView::MissingTemplate => e
if e.message =~ %r{Missing template #{templ}}
raise ActionController::RoutingError, 'Not Found'
else
raise e
end
end
end
These are my routes:
Rails.application.routes.draw do
root 'static#show', page: 'home'
get ':page', to: 'static#show', as: :static, constraints: { page: /a-zA-Z\-_\/+/ }
end
The root route works fine, I am able to access the view just fine. I get no errors.
Now, on my header partial, I have this, edited for simplicity/relevance:
<%= link_to('Home', static_path(:home)) %>
There is no other ruby code in the partial or the main template. I'm not sure what I'm doing wrong. The error just does NOT make sense.
ActionController::UrlGenerationError - No route matches {:action=>"show", :controller=>"static", :format=>nil, :page=>:home} missing required keys: [:page]
Where exactly is the required key missing from? I don't have any objects other or models.
Now this works just fine:
<%= link_to('Home', controller: 'static', action: 'show', page: 'home') %>
So how do I make static_path work like that?
Thanks.
I think there's a problem with the regexp your using for the constraint, I'd suggest dropping it from the route definition, as you already check if template is present in the controller.
Also, you should check out high_voltage gem which handles creating static pages quite nicely.
My first guess would be:
<%= link_to 'Home', static_path("home") %> #-> try passing a string, rather than symbol
This should allow you to reference the required path
--
class StaticController < ApplicationController
def show
templ = File.join(params[:controller], params[:page])
puts params, templ
render templ
rescue ActionView::MissingTemplate => e
if e.message =~ %r{Missing template #{templ}}
raise ActionController::RoutingError, 'Not Found'
else
raise e
end
end
end
I would personally make this a lot simpler:
class StaticController < ApplicationController
def show
render "pages#{params[:page]}
end
end

rails xml.builder missing template error

Error:
Template is missing
Missing template miscellaneous/sitemap, application/sitemap with {:locale=>[:en], :formats=>[:xml], :handlers=>[:erb, :builder]}. Searched in: * "/Users/yliu/Google Drive/ruby projects/Blog/lenswish/app/views" * "/usr/local/rvm/gems/ruby-1.9.3-p194/bundler/gems/twitter-bootstrap-rails-4b8a511e6518/app/views" * "/usr/local/rvm/gems/ruby-1.9.3-p194/gems/devise-3.1.0/app/views"
rake routes:
GET /sitemap.xml(.:format) miscellaneous#sitemap {:format=>"xml"}
routes.rb:
get "sitemap.xml", :to => "miscellaneous#sitemap", defaults: { format: "xml" }
controller:
class MiscellaneousController < ApplicationController
def sitemap
#card_templates = CardTemplate.all
respond_to do |format|
format.xml
end
end
end
Template position:
app/views/miscellaneous/sitemap.xml.builder
content in template sitemap.xml.builder:
# Sitemaps 0.9 XML format: http://www.sitemaps.org/protocol.php
xml.instruct!
xml.urlset :xmlns => 'http://www.sitemaps.org/schemas/sitemap/0.9' do
xml.url do
xml.loc root_url
xml.changefreq 'daily'
xml.lastmod #card_templates.first.updated_at.iso8601
xml.priority '0.8'
end
end
I already checked file permission issues. Still not working. Anyone help please. Thanks in advance.
This looks wrong to me:
GET /sitemap.xml(.:format) miscellaneous#sitemap {:format=>"xml"}
Shouldn't it be like this?
GET /sitemap(.:format) miscellaneous#sitemap {:format=>"xml"}
I would change your route to:
get "sitemap", :to => "miscellaneous#sitemap"
Your controller code should look about the same
class MiscellaneousController < ApplicationController
def sitemap
#card_templates = CardTemplate.all
respond_to do |format|
format.xml
end
end
end
This turns out to be an IDE issue, the file name I saw from the textmate ui differs from what I saw from the terminal. Fixed after I renamed the file.

Resources