const_missing': uninitialized constant Rack::IpRestrictor (NameError) - ruby-on-rails

Why the error?
Here's the setup:
config/initializers/rack_ip_restrictor.rb
Rack::IpRestrictor.configure do
respond_with [403, {'Content-Type' => 'text/html'}, '']
ips_for :test do
add '127.0.0.1'
add '127.0.0.2/8'
end
restrict /^\/admin/, '/admin', :only => :test
end
config/application.rb
class Application < Rails::Application
...
config.middleware.use Rack::IpRestrictor.middleware
...
end
/lib/rack_ip_restrictor.rb
require 'ipaddr'
require 'active_support/core_ext/array/extract_options'
# namespace Rack
module Rack
# namespace IpRestrictor
module IpRestrictor
class << self
attr_reader :config
# #see Config#initialize
def configure(&block)
#config = IpRestrictor::Config.new
#config.instance_eval &block
end
# Rack middleware
# #return [Middleware] The configured plug & play Rack middleware
def middleware
IpRestrictor::Middleware
end
end
end
end
require 'rack_ip_restrictor/ip_group'
require 'rack_ip_restrictor/middleware'
require 'rack_ip_restrictor/config'
require 'rack_ip_restrictor/restriction'
Any idea why rails can't find Rack::IpRestrictor ?
Thanks

You're not requiring this file anywhere. That is why it cannot find the constant. Files in the lib directory are not automatically loaded in Rails 3. Require this file manually.

Related

NameError uninitialized constant MyWorker::MyController

I'm using sidekiq to do a simple sample worker. When a make a request to my endpoint, it finished successfully but in the worker I got the following error:
*** NameError Exception: uninitialized constant SaveMessageWorker::Message
I'm using:
ruby 2.5.7
rails 5.2.3
sidekiq 6.0.0
This is part of my api rails project structure:
app
---controllers
------api
---------v1
------------messages_controller.rb
---workers
------save_message_worker.rb
config
---initializers
------sidekiq.rb
---application.rb
These are my files and paths:
app/workers/save_message_worker.rb
class SaveMessageWorker
include Sidekiq::Worker
def perform(message_list)
# byebug
# When I tried the below line, I got: *** NameError Exception: uninitialized constant SaveMessageWorker::Message
message = Message.new(message: message_list)
end
end
app/controllers/api/v1/messages_controller.rb
def multiple_concurrent_workers
begin
SaveMessageWorker.perform_async("Hello World!")
return (render json: {status: "success", data:"processed successfully"})
rescue => exception
logger.error CONTROLLER_NAME + ': An error happened in method multiple_concurrent_workers: ' + exception.to_json
return (render json: {status: "error", message: exception})
end
end
config/routes.rb
Rails.application.routes.draw do
require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'
devise_for :users
namespace :api, defaults: { format: "json" } do
namespace :v1 do
resources :messages do
collection do
post :multiple_concurrent_workers
end
end
end
end
end
config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
config.redis = { url: 'redis://' + Rails.application.credentials[Rails.env.to_sym][:redis][:host].to_s + ':' +Rails.application.credentials[Rails.env.to_sym][:redis][:port].to_s + '/' + Rails.application.credentials[Rails.env.to_sym][:redis][:database].to_s }
end
Sidekiq.configure_client do |config|
config.redis = { url: 'redis://' + Rails.application.credentials[Rails.env.to_sym][:redis][:host].to_s + ':' +Rails.application.credentials[Rails.env.to_sym][:redis][:port].to_s + '/' + Rails.application.credentials[Rails.env.to_sym][:redis][:database].to_s }
end
config/application.rb
require_relative 'boot'
require "rails"
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
require "rails/test_unit/railtie"
Bundler.require(*Rails.groups)
module IbeenDev
class Application < Rails::Application
config.load_defaults 5.2
config.middleware.use Rack::MethodOverride
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore
config.middleware.use ActionDispatch::Flash
config.log_level = :error
config.autoload_paths << Rails.root.join("lib")
config.eager_load_paths << Rails.root.join("lib")
config.api_only = true
Koala.config.api_version = 'v2.0'
config.active_job.queue_adapter = :sidekiq
end
end
There was an opened issued in the github project, but author said that this is not an exactly sidekiq problem.
Can anyone help me to find the solution? Any help will be appreciated

undefined local variable or method `flash' for #<Devise::OmniauthCallbacksController:0x007fb5d1741e48>

I am building a Rails-API using Omniauth-facebook and Devise-token-auth with Angular and ng-token-auth for the frontend.
However when logging in with facebook I am presented with the error:
undefined local variable or method `flash' for #<Devise::OmniauthCallbacksController:0x007fd027a51e10>
It seems omniauth automatically uses flash middleware however the rails-api doesn't include this and I have been unsuccessfully disabling the use of flash with omniauth.
My configuration is as below:
application.rb:
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module PathfinderApi
class Application < Rails::Application
config.active_record.raise_in_transactional_callbacks = true
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
config.api_only = true
config.middleware.use ActionDispatch::Flash
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore
end
end
devise_token_auth.rb:
DeviseTokenAuth.setup do |config|
Rails.application.secrets.facebook_app_secret
config.change_headers_on_each_request = true
end
devise.rb:
Devise.setup do |config|
config.navigational_formats = [:json]
end
omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV['APP_KEY'], ENV['APP_SECRET']
end
I have not managed to disable the flash error with:
config.navigational_formats = [:json]
and devise/omniauth is still using flash middleware and throws the error, any help appreciated!
Had the same problem. Searched the devise source code for 'flash'. Found about 17 matches, all using set_flash_message! (with exclamation mark), except for the failure method in the OmniauthCallbacksController, which uses set_flash_message (without exclamation mark). Looking at the definition we see:
\app\controllers\devise\omniauth_callbacks_controller.rb
# Sets flash message if is_flashing_format? equals true
def set_flash_message!(key, kind, options = {})
if is_flashing_format?
set_flash_message(key, kind, options)
end
end
\lib\devise\controllers\helpers.rb
def is_flashing_format?
is_navigational_format?
end
def is_navigational_format?
Devise.navigational_formats.include?(request_format)
end
The actual flash message is generated in the method without exclamation mark (I would have progged it the other way around...). The missing exclamation mark is the reason why setting the navigational_formats as mentioned in other solutions doesn't work here.
Conclusion: they forgot the exlamation mark.
The fix: monkey-patch the failure method from the OmniauthCallbacksController. Do this in an initializer, for example in
\config\initializers\devise.rb
Rails.application.config.to_prepare do # to_prepare ensures that the monkey patching happens before the first request
Devise::OmniauthCallbacksController.class_eval do # reopen the class
def failure # redefine the failure method
set_flash_message! :alert, :failure, kind: OmniAuth::Utils.camelize(failed_strategy.name), reason: failure_message
redirect_to after_omniauth_failure_path_for(resource_name)
end
end
end
Had the same problem in Rails (5.0.0.1) + devise_token_auth (0.1.39).
Besides the override in #Koen's answer, the following addition is also necessary in my case:
# in config/application.rb
config.middleware.use ActionDispatch::Cookies
I managed to solve this by adding this to the devise.rb config:
config.navigational_formats = []
This way devise will never attempt to use flash and never throw a 500 error.
Taken from https://github.com/heartcombo/devise/issues/4275

how do I test AccountsController < AbstractedResourcesController

My app has a default controller abstracted into a gem (gem 'abstracted') and all my controllers inherits from this abstracted controller.
# Gemfile
gem 'abstracted', path: '../../gems/abstracted'
# app/controllers/accounts_controller.rb
class AccountsController < AbstractResourcesController
end
Now when I write controller (mini)tests for one of this controllers like this:
require "test_helper"
describe AccountsController do
...
I get this error once hitting: rake test from the prompt:
NameError: uninitialized constant AbstractResourcesController
/path_to_rails/projects/cas_server/app/controllers/accounts_controller.rb:1:in `<top (required)>'
My test/test_helper.rb looks like this:
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'minitest/autorun'
require 'action_controller/test_case'
require 'capybara/rails'
require 'rails/test_help'
require 'minitest-rails'
require 'minitest/pride'
# require 'miniskirt'
# require 'factories'
# require 'mocha'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
class ActionController::TestCase
include Devise::TestHelpers
end
class MiniTest::Unit::TestCase
# include MiniTest::ActiveRecordAssertions
# DatabaseCleaner.strategy = :transaction
#
# def setup
# DatabaseCleaner.start
# end
#
# def teardown
# DatabaseCleaner.clean
# end
end
class MiniTest::Spec
include ActiveSupport::Testing::SetupAndTeardown
# alias :method_name :__name__ if defined? :__name__
def build_message(*args)
args[1].gsub(/\?/, '%s') % args[2..-1]
end
end
class ControllerSpec < MiniTest::Spec
include ActionController::TestCase::Behavior
include Devise::TestHelpers
include Rails.application.routes.url_helpers
# Rails 3.2 determines the controller class by matching class names that end in Test
# This overides the #determine_default_controller_class method to allow you use Controller
# class names in your describe argument
# cf: https://github.com/rawongithub/minitest-rails/blob/gemspec/lib/minitest/rails/controller.rb
def self.determine_default_controller_class(name)
if name.match(/.*(?:^|::)(\w+Controller)/)
$1.safe_constantize
else
super(name)
end
end
before do
#controller = self.class.name.match(/((.*)Controller)/)[1].constantize.new
#routes = Rails.application.routes
end
subject do
#controller
end
end
# Functional tests = describe ***Controller
MiniTest::Spec.register_spec_type( /Controller$/, ControllerSpec )
Add this in your controller spec file before describe AccountsController do,
module AbstractResourcesController
class Base
def self.protect_from_forgery; end
end
end
require 'abstract_resources_controller'

REXML::ParseException in BoxfileController#index

I have been trying to create dropbox like aws base cloud hosting app in rails. I have already add most of feature in app. But recently i am facing issuse with following error.
REXML::ParseException in BoxfileController#index
Missing end tag for 'meta' (got "head") Line: 6 Position: 354 Last 80 unconsumed characters:
end
#userfiles = AWS::S3::Bucket.objects(BUCKET_NAME, :prefix => current_user.folder)
end
These are my following file in app.
airbox/boxfile_controller.rb
class BoxfileController < ApplicationController
before_filter :authenticate_user!
def index
if current_user.folder.nil?
current_user.folder = generate_random_user_folder_name
current_user.save
end
#userfiles = AWS::S3::Bucket.objects(BUCKET_NAME, :prefix => current_user.folder)
end
end
def add
end
def upload
begin
AWS::S3::S3Object.store(sanitize_filename(params[:boxfile].original_filename),
params[:boxfile].read, BUCKET_NAME, :access => :public_read)
redirect_to boxfile_path, :notice => "Your file was successfully uploaded to ShareBox"
rescue
redirect_to boxfile_path, :error => "Your file couldn't be uploaded to ShareBox"
end
end
def delete
if (params[:file_id])
AWS::S3::S3Object.find(params[:file_id], BUCKET_NAME).delete
redirect_to boxfile_path, :notice => params[:file_id].sub(current_user.folder + '/','') + " was deleted"
else
redirect_to boxfile_path, :error => "Could not delete " + params[:file_id].sub(current_user.folder + '/','')
end
end
def sanitize_filename(file_name)
just_filename = File.basename(file_name)
File.join(current_user.folder, just_filename.sub(/[^\w\.\-]/,'_'))
end
def generate_random_user_folder_name()
letters = [('a'..'z'), ('A'..'Z')].map { |i| i.to_a }.flatten
return (0...8).map{ letters[rand(letters.length)] }.join
end
end
airbox/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Sharebox
class Application < Rails::Application
config.action_view.embed_authenticity_token_in_remote_forms = true
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
AWS::S3::Base.establish_connection!(
:access_key_id => 'AKIAJB3GGLYUKI64NJKQ',
:secret_access_key => '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'
)
end
end
and environment.rb file
# Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Sharebox::Application.initialize!
BUCKET_NAME = "airboxinrails"
AWS::S3::Base.establish_connection!(
:access_key_id => ACCESS_KEY,
:secret_access_key => SECREY_KEY
)
and for more details i have uploaded to github
https://github.com/aruzmeister/AirBox
Can anybody help me with the bug..?

How to include Rails Helpers on RSpec

I'm trying to include some helpers to test with rspec but no luck.
What I did:
created a support/helpers.rb file under my spec folder.
support/helpers.rb
module Helpers
include ActionView::Helpers::NumberHelper
include ActionView::Helpers::TextHelper
end
and tried to require this file in spec_helper.rb.
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'rubygems'
require 'spork'
require 'support/helpers'
Spork.prefork do
.
.
end
this generates the following error:
/spec/support/helpers.rb:2:in `<module:Helpers>': uninitialized constant Helpers::ActionView (NameError)
How should I do this helpers to be available with Rspec?
Thanks.
I normally include this code to require everything under my spec/support subdirectory once the Rails stack is available:
Spork.prefork do
# ...
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
RSpec.configure do |config|
config.include MyCustomHelper
# ...
end
end
Note that this will include MyCustomHelper in all example types (controllers, models, views, helpers, etc.). You can narrow that down by passing a :type parameter:
config.include MyControllerHelper, :type => :controller
Include the Module you need directly in the spec file:
include PostsHelper
(Rails 7) You can also extend the helpers lookup location in e.g. application.rb like
# https://guides.rubyonrails.org/configuring.html#configuring-action-view
config.helpers_paths << 'path/to/unusual/helper/location.rb'

Resources