Rails/Passenger sub URI error - ruby-on-rails

I am attempting to deploy a Rails 3.0.0 application to a sub URI using passenger 2.2.15.
I believe I've made the correct RailsBaseURI changes to my http.conf , have symlinked the sub URI to the public directory of my app and added the following line of code to environments/production.rb:
config.action_controller.relative_url_root = "/sub_uri"
I've done this several times pre-rails3.0.0. That said, the app won't launch. It fails with the following Passenger error:
Error Message: wrong number of arguments(1 for 0)
Exception class: ArgumentError
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.0/lib/action_controller/railtie.rb 54 in `relative_url_root='
Is there an incompatibility between passenger 2.2.15 and rails 3.0.0 that affects sub URI's?
Any help sorting out this error is greatly appreciated.

The setter is depreciated, it's nowhere to be found in actionpack/lib/action_controller/railtie.rb.
As seen here (actionpack/lib/action_controller/depreciated/base.rb):
module ActionController
class Base
# Deprecated methods. Wrap them in a module so they can be overwritten by plugins
# (like the verify method.)
module DeprecatedBehavior #:nodoc:
def relative_url_root
ActiveSupport::Deprecation.warn "ActionController::Base.relative_url_root is ineffective. " <<
"Please stop using it.", caller
end
def relative_url_root=
ActiveSupport::Deprecation.warn "ActionController::Base.relative_url_root= is ineffective. " <<
"Please stop using it.", caller
end
end
end
end
In actionpack/lib/action_controller/metal/compatibility.rb you can see it's setter is an ENV variable:
self.config.relative_url_root = ENV['RAILS_RELATIVE_URL_ROOT']
So you need to set the ENV variable: RAILS_RELATIVE_URL_ROOT="/sub_uri"

To set the environment variable add:
SetEnv RAILS_RELATIVE_URL_ROOT /sub_uri
To the VirtualHost section (or similar) of your apache config then make sure it's being read by restarting apache and passenger.
cd <your_rails_project>
sudo apache2ctl graceful
touch tmp/restart

Related

Running webpacker:compile for a engine in my host app causes rails to abort

I have a rails engine/plugin in which i am trying to use webpacker using THIS article as a guide. So basically in my engine, i have the following code :-
lib/saddlebag.rb
require "saddlebag/engine"
module Saddlebag
# ...
class << self
def Webpacker
#Webpacker ||= ::Webpacker::Instance.new(
root_path: Saddlebag::Engine.root,
config_path: Saddlebag::Engine.root.join('config', 'webpacker.yml')
)
end
end
# ...
end
and in the lib/saddlebag/engine.rb file i have the following code :
module Saddlebag
class Engine < ::Rails::Engine
isolate_namespace Saddlebag
# use packs from saddlebag via Rack static
# file service, to enable webpacker to find them
# when running in the host application
config.app_middleware.use(
Rack::Static,
# note! this varies from the webpacker/engine documentation
urls: ["/saddlebag-packs"], root: Saddlebag::Engine.root.join("public")
)
initializer "webpacker.proxy" do |app|
insert_middleware = begin
Saddlebag.webpacker.config.dev_server.present?
rescue
nil
end
next unless insert_middleware
app.middleware.insert_before(
0, Webpacker::DevServerProxy, # "Webpacker::DevServerProxy" if Rails version < 5
ssl_verify_none: true,
webpacker: Saddlebag.webpacker
)
end
end
end
Also i have all of the files required by webpacker mainly :-
config/webpacker.yml and config/webpack/*.js files
bin/webpack and bin/webpack-dev-server files
package.json with required deps.
So the engine and my actually app are in sibling directories so:-
saddlebag
open-flights (main app)
in open flights i link saddlebag with the following line in the gem file :-
gem 'saddlebag', path: '../saddlebag'
Now when i run bin/rails saddlebag:webpacker:compile , i get the following error :-
rails aborted! Don't know how to build task
'saddlebag:webpacker:compile' (See the list of available tasks with
rails --tasks)
Why am i getting this error i have webpacker as a dependency in my saddlebag app. So not sure why this error still occures.
P.S. I found a similar guide for rails engine for enabling webpacker HERE (but uses docker)

`<module:Rails>': superclass mismatch for class Server (TypeError)

I have seen this and several others question, but their problems are not similar to mine.
I have added the following code to the config/boot.rb , to run my server on port 8081
module Rails
class Server
def default_options
super.merge({Port: 8081})
end
end
end
Then I tried to run rails s, and i face with this erorr:
/usr/local/rvm/gems/ruby-2.2.1/gems/railties-4.2.4/lib/rails/commands/server.rb:7:in `<module:Rails>': superclass mismatch for class Server (TypeError)
from /usr/local/rvm/gems/ruby-2.2.1/gems/railties-4.2.4/lib/rails/commands/server.rb:6:in `<top (required)>'
A better way to do what you want:
require 'rails/commands/server'
module DefaultOptions
def default_options
super.merge!(Port: 8081)
end
end
Rails::Server.prepend(DefaultOptions)
The reason for the error message is because you are attempting to redefine the Rails::Server class and changing it's inheritance structure. Rails::Server inherits from ::Rack::Server, however your code is trying to say it no longer does. Therefore, you get your superclass mismatch error.
For Rails 5.1 the following line in config/boot.rb will do the trick:
ENV['PORT'] = '8081'
Link to the source.
In Rails 5.2
in config/puma.rb I added this code.
#port ENV.fetch("PORT") { 3000 }
bind 'tcp://0.0.0.0:3001'
And it works!

How to disable "Cannot Render Console from..." on Rails

I'm using Ubuntu/vagrant as my development environment.
I'm getting these messages on rails console:
Started GET "/assets/home-fcec5b5a277ac7c20cc9f45a209a3bcd.js?body=1" for 10.0.2.2 at 2015-04-02 15:48:31 +0000
Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Is it possible to disable those "cannot render..." messages or allow them in any way?
You need to specifically allow the 10.0.2.2 network space in the Web Console config.
So you'll want something like this:
class Application < Rails::Application
config.web_console.permissions = '10.0.2.2'
end
Read here for more information.
As pointed out by pguardiario, this wants to go into config/environments/development.rb rather than config/application.rb so it is only applied in your development environment.
You can whitelist single IP's or whole networks.
Say you want to share your console with 192.168.0.100. You can do this:
class Application < Rails::Application
config.web_console.whitelisted_ips = '192.168.0.100'
end
If you want to whitelist the whole private network, you can do:
class Application < Rails::Application
config.web_console.whitelisted_ips = '192.168.0.0/16'
end
If you don't wanna see this message anymore, set this option to false:
class Application < Rails::Application
config.web_console.whiny_requests = false
end
Be careful what you wish for, 'cause you might just get it all
This is probably only for development purposes so you might prefer to place it under config/environments/development.rb instead of config/application.rb.
Hardcoding an IP into a configuration file isn't good. What about other devs? What if the ip changes?
Docker-related config should not leak into the rails app whenever possible. That's why you should use env vars in the config/environments/development.rb file:
class Application < Rails::Application
# Check if we use Docker to allow docker ip through web-console
if ENV['DOCKERIZED'] == 'true'
config.web_console.whitelisted_ips = ENV['DOCKER_HOST_IP']
end
end
You should set correct env vars in a .env file, not tracked into version control.
In docker-compose.yml you can inject env vars from this file with env_file:
app:
build: .
ports:
- "3000:3000"
volumes:
- .:/app
links:
- db
environment:
- DOCKERIZED=true
env_file:
- ".env"
Based on the feebdack received in comments, we can also build a solution without environment variables:
class Application < Rails::Application
# Check if we use Docker to allow docker ip through web-console
if File.file?('/.dockerenv') == true
host_ip = `/sbin/ip route|awk '/default/ { print $3 }'`.strip
config.web_console.whitelisted_ips << host_ip
end
end
I'll leave the solutions with env var for learning purposes.
Auto discovery within your config/development.rb
config.web_console.whitelisted_ips = Socket.ip_address_list.reduce([]) do |res, addrinfo|
addrinfo.ipv4? ? res << IPAddr.new(addrinfo.ip_address).mask(24) : res
end
Of course might need to add
require 'socket'
require 'ipaddr'
Within your file.
Anyone on any of my private networks is welcome.
I run in a docker container and I don't care which network it wants to use this week.
config/environments/development.rb add line
config.web_console.whitelisted_ips = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16']
For development environment: Detect if it's docker, then determine the IP address and whitelist it
# config/environments/development.rb
require 'socket'
require 'ipaddr'
Rails.application.configure do
...
# When inside a docker container
if File.file?('/.dockerenv')
# Whitelist docker ip for web console
# Cannot render console from 172.27.0.1! Allowed networks: 127.0.0.1
Socket.ip_address_list.each do |addrinfo|
next unless addrinfo.ipv4?
next if addrinfo.ip_address == "127.0.0.1" # Already whitelisted
ip = IPAddr.new(addrinfo.ip_address).mask(24)
Logger.new(STDOUT).info "Adding #{ip.inspect} to config.web_console.whitelisted_ips"
config.web_console.whitelisted_ips << ip
end
end
end
For me this prints the following and the warning goes away 🎉
Adding 172.27.0.0 to config.web_console.whitelisted_ips
Adding 172.18.0.0 to config.web_console.whitelisted_ips
My solution was to combine
the answer from user2481743 ⭐️ https://stackoverflow.com/a/42142563/2037928
the comment from jottr ⭐️ How to disable "Cannot Render Console from..." on Rails
If you run your site locally (on the host) it generally works out, since 127.0.0.1 is always permitted. But if you're going to put your site into a container (not in production, locally), you might want to add this into config/environments/development.rb:
require 'socket'
require 'ipaddr'
Rails.application.configure do
...
config.web_console.permissions = Socket.getifaddrs
.select { |ifa| ifa.addr.ipv4_private? }
.map { |ifa| IPAddr.new(ifa.addr.ip_address + '/' + ifa.netmask.ip_address) }
...
end
P.S. Most of the time you want it to whine (don't want to do config.web_console.whiny_requests = false). Because it might mean you're running web-console in production (which you shouldn't do).
For me, whitelisted_ips didn't seem to work in a new project. The Readme states the corresponding configuration entry is supposed to be permissions now:
Rails.application.configure do
config.web_console.permissions = '192.168.0.0/16'
end
https://github.com/rails/web-console/blob/master/README.markdown
If you want to stop seeing this error message you can add this line in development.rb
config.web_console.whiny_requests = false
Note that only the last 'config.web_console.whitelisted_ips' will be used. So
config.web_console.whitelisted_ips = '10.0.2.2'
config.web_console.whitelisted_ips = '192.168.0.0/16'
will only whitelist 192.168.0.0/16, not 10.0.2.2.
Instead, use:
config.web_console.whitelisted_ips = ['10.0.2.2', '192.168.0.0/16']
class Application < Rails::Application
config.web_console.whitelisted_ips = %w( 0.0.0.0/0 ::/0 )
end
If you are using Docker most likely you don't want neither to introduce new ENV variables nor to hardcode your specific IP address.
Instead you may want to check that you are in Docker using /proc/1/cgroup, and to allow your host IP (both for web_console and better_errors). Add to your config/environments/development.rb
# https://stackoverflow.com/a/20012536/4862360
if File.read('/proc/1/cgroup').include?('docker')
# https://stackoverflow.com/a/24716645/4862360
host_ip = `/sbin/ip route|awk '/default/ { print $3 }'`.strip
BetterErrors::Middleware.allow_ip!(host_ip) if defined?(BetterErrors::Middleware)
config.web_console.whitelisted_ips << host_ip
end
I just want to add this because my own mistake caused me to get the same error.
I was missing this from the controller
load_and_authorize_resource except: [:payment_webhook]
Basically I was using cancancan to place authorization on that route, which was causing a 404 to be returned. I saw the message and assumed the two were related, when in fact they were not
Cannot render console from xxxxxx Allowed networks: xxxxx
So if you are getting an error message, it's possible that it has nothing to do with the Cannot render console from xxxxxx Allowed networks: xxxxx you see - look for other problems!

Ruby XMLRPC localhost Runtime Error : Wrong Size

I am trying to connect to the XMLRPC API of a dokuwiki website.
I am successfully doing that from my own laptop, with a SSL connection, however, when I try to do it from my production server (which hosts both the wiki and the rails app from which the ruby code is executed), I run into a
Runtime Error
Wrong size. Was 163, should be 113
Here's how I initialize the connection :
#wiki = ::XMLRPC::Client.new3(
host: "wiki.example.com",
path: "/lib/exe/xmlrpc.php",
use_ssl: true)
# Temp Hack because SSL Fails
#wiki.instance_variable_get(:#http).instance_variable_set(:#verify_mode, OpenSSL::SSL::VERIFY_NONE)
end
#authenticated = false
authenticate!
end
def authenticate!
# Fails at below line :
#authenticated = #wiki.call("dokuwiki.login", ENV['WIKI_USER'], ENV['WIKI_PASSWORD'])
Rails.logger.info (#authenticated ? "Authenticated on Wiki !" : "Authentication failed on wiki !")
end
I've read many posts saying that there is a bug in the XMLRPC lib of Ruby. I was running ruby 2.1.5pxx on my laptop and ruby 1.9.xx at my server so I did a rvm install 2.1.5, yet the problem is still here
(btw, I assumed it was enough to do a rvm use 2.1.5 and then touch restart to restart my rails server, but how can I check which version of ruby it's using ?)
What is wrong ?
EDIT
On my laptop, I am running ruby 2.1.5p273 (2014-11-13 revision 48405) [x64-mingw32]
On my production server, I am running ruby-2.1.5 [ i686 ]
I tried another library, libxml-xmlrpc, and I get the following error when running the same command:
Net::HTTPBadResponse: wrong status line: "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">"
But again, the same code is running fine with the default ruby xmlrpc client on my Windows + rubyx64 2.1.5, so I really don't get it!
Edit2 : I tried adding
#wiki.http_header_extra = { "accept-encoding" => "identity" }
But then I get a
Authorization failed. HTTP-Error: 401 Unauthorized
The first call #wiki.call("dokuwiki.login", "myUsr", "myPwd") worked, but apparently it failed to authenticate me (Of course I am still using the same login information that should work)
EDIT 3
After investigation, a successful login from any other computer than localhost will set a cookie like
#cookie="DokuWiki=[small string] ; [very big string]
Whereas if I do it on localhost :
I will write [...] for random strings
#cookie="[small string 2]=deleted; DokuWiki=[small string]; [very big string]"
So I have an extra variable info stored in my cookie, which is "[small string 2]=deleted;
I believe this is what makes my authentication fails. Anyone knows what this is ???
So this localhost connection was messing up with the cookie. Apparently, even the ruby library doesn't know why, and the "Wrong size" comes from this unexpected string [random string]=deleted added at the beginning of the cookie.
Unless someone can explain WHY such a string is added, I will accept my solution of simply adding
#wiki.http_header_extra = { "accept-encoding" => "identity" }
which removes the "Wrong size" error, then
if /deleted/.match(#wiki.cookie)
#wiki.cookie = #wiki.cookie.gsub(/.*deleted; /, '')
end
To remove the beginning of the cookie

ExecJS::RuntimeError running the Getting Started with Rails blog on cygwin (windows7)

I am trying to run the Getting Started with Rails blog on cygwin (windows7). I get the following error message:
ExecJS:: RuntimeError in Welcome#index
module.js:340
throw err;
^
Error: Cannot find module 'C:\tmp\execjs20130903-50672-1vn7gqc.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
(in /usr/lib/ruby/gems/1.9.1/gems/turbolinks-1.3.0/lib/assets/javascripts /turbolinks.js.coffee)
node is installed.
This is after
$rails generate controller welcome index
$rails s
I am running Rails 4.0 on cygwin
Any ideas why this might be happening?
Thanks
umbregachoong
I encountered this error and it had to do with the path to the temp file being wrong. I was able to fix it by changing the following two files in \gems\[ruby version]\gems\execjs-2.0.2\lib\execjs.
(Possibly found in \usr\lib\ruby\, but that depends on how your Ruby is installed. I'm using RVM so mine is different.)
external_runtime.rb
compile_to_tempfile(source) do |file|
extract_result(#runtime.send(:exec_runtime, file.path))
end
end
should change to
compile_to_tempfile(source) do |file|
filepath = file.path
if ExecJS.cygwin? && #runtime.name == "JScript"
IO.popen("cygpath -m " + file.path) { |f| filepath = f.read }
filepath = filepath.gsub("\n","")
end
extract_result(#runtime.send(:exec_runtime, filepath))
end
end
module.rb
Add this right before the last two ends.
def cygwin?
#cygwin ||= RbConfig::CONFIG["host_os"] =~ /cygwin/
end
After this restart your Rails server and with any luck it should work.
Source: https://github.com/sstephenson/execjs/issues/78
don't do anything just go to application/assets/javascript/application.js and remove
'//'
from
//=require turbolinks
to
=require turbolinks
that will basically uncomment the line from the file
This step made my work done when i faced similar error in Default rails server going through RAILS Tutorial. I am using Windows 10 PC and this solved my case

Resources