Rails app GET routes not working in production mode - ruby-on-rails

I've inherited a Rails application that isn't completely functional when running in production mode. GET requests to the server are resulting in a no route match found error; however, when the server is run in development mode all routes will work, giving an expected 200 status.
Reviewing the code reveals that the application expects a prefixed subdomain in addition to the domain used in a successful URL request.
class ApplicationContext
def initialize(subdomain, host_with_port)
if subdomain.present?
case subdomain
when Rails.application.config.workninja.admin_subdomain
#environment = :admin
when Rails.application.config.workninja.mobile_subdomain
#environment = :mobile
else
#environment = :customer
end
else
raise 'Could not initialize ApplicationContext without subdomain'
end
#url_options = {subdomain: subdomain, host: host_with_port}
setup_method = "setup_#{#environment.to_s}_environment".to_sym
if respond_to?(setup_method, true)
send(setup_method, subdomain, host_with_port)
else
raise 'Unknown context environment'
end
end
attr_reader :environment
attr_reader :url_options
attr_reader :agency
def self.current
Thread.current['workninja:tenant_context']
end
def admin?
#environment == :admin
end
def mobile?
#environment == :mobile
end
def customer?
#environment == :customer
end
def ui_url_for(path, subdomain = url_options[:subdomain])
base = "#{Rails.application.config.workninja.https ? 'https' :
'http'}://#{subdomain}.#{Rails.application.config.workninja.domain}"
if Rails.application.config.workninja.html5mode
puts URI.join(base, path).to_s
else
puts URI.join(base, "/#/#{path}".gsub(/\/+/, '/')).to_s
end
end
The original front end supplied with the application constructs the request's URLs depending on the environment the sever was launched in.
{
"environment": "development",
"url": "http://admin.workninja.local:3000"
}
{
"environment": "production",
"url": "/api"
}
To me the production URL doesn't make sense as all it does is append "/api" to the root domain that the front end is hosted on. I can only assume that it's just a placeholder that needs to be replaced with the domain name that the rails server is hosted on once it's running in a live environment. The "/api" path isn't used throughout the functional development version of the app which makes me further assume it's a placeholder.
Using the above as a guide I replaced "/api" with "http://admin.workninja.com.au". After hosting the application on a live domain I confirmed it was working by running:
curl http://admin.workninja.com.com.au/auth -X POST
This gave me an expected error about credentials not being supplied but it shows that the server is actually receiving something. If you haven't realised the rails server when launched in production mode will respond to a POST request but still not a GET.
This is where my understanding of the problem breaks down. If
http://admin.workninja.local:3000/roles
works ("/roles being one of the applications routes") in a development environment why doesn't
http://admin.workninja.com.au/roles
work in a production environment as well? Can you assume from this fact that something isn't broken in the ruby codebase?
Below are some of the files relating to the configuration of the rails application in a production environment.
/config/deploy/production.rb
set :branch, 'master'
server 'ec2-54-66-230-174.ap-southeast-2.compute.amazonaws.com', user: 'ubuntu', roles: %w{app web db worker}
/config/environments/production.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
# This needs to be set to true in order for rails to launch in a production environment
config.eager_load = false
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :warn
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Application hostname
config.surgeforce.domain = 'surgeforce.com.au'
config.surgeforce.https = false
config.surgeforce.html5mode = true
end
/config/puma.rb
threads 1, 6
workers Integer(ENV['PUMA_WORKERS'] || 3)
on_worker_boot do
require "active_record"
cwd = File.dirname(__FILE__)+"/.."
ActiveRecord::Base.connection.disconnect! rescue ActiveRecord::ConnectionNotEstablished
ActiveRecord::Base.establish_connection(ENV["DATABASE_URL"] || YAML.load_file("#{cwd}/config/database.yml")[ENV["RAILS_ENV"]])
end
If you believe any other piece of the applications code to be critical in the investigation let me know and I'll include it.

The problem is that Rails' subdomain method is very simple and doesn't know anything about the structure of com.au domains. For "admin.workninja.com.au" which you use on production, the subdomain method would return "admin.workninja". From the docs:
Returns all the \subdomains as a string, so "dev.www" would be
returned for "dev.www.rubyonrails.org". You can specify a different tld_length, such as 2 to catch "www" instead of "www.rubyonrails" in "www.rubyonrails.co.uk".
And – without knowing your configuration– "admin.workninja" will very likely not match your config.workninja.admin_subdomain configuration anymore.
The solution is to configure a tld length of 2 on production. Just add the following to the configuration block in your config/environments/production.rb:
config.action_dispatch.tld_length = 2 # Defaults to 1

Related

ActionController::RoutingError No route matches [GET] & [OPTION] for "/cloudfoundryapplication"

I am running Rails 5.1.3 with Puma on Pivotal Web Services. Since upgrading to this version from Rails 4, i am seeing the following errors appear in the logs:
1. ActionController::RoutingError (No route matches [GET] "/cloudfoundryapplication")
2. ActionController::RoutingError (No route matches [OPTION] "/cloudfoundryapplication")
I can't find any details on the "/cloudfoundryapplication" on Pivotal but as it an external application i figured it might be related to Cross-Origin Resource Sharing (CORS). I then used the 'rack-cors' gem to try to fix the issue. The effect was that the [OPTION] errors disappeared but not the [GET] errors.
Here is my config/application.rb:
require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
require 'pdfkit'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MyFaro
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# 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 = 'Brussels'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
#config.i18n.load_path = Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :nl
#config.skylight.probes += %w(mongoid mongo)
config.middleware.use PDFKit::Middleware, {:print_media_type => true}, :only => %r[/print_story]
config.after_initialize do
ApplicationController.helpers.cache_set_look_up_hash
ApplicationController.helpers.cache_set_system_parameter_hash
end
end
end
and my config/environments/production.rb:
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
#CORS
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.cache_store = :memory_store
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :error
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "my_faro_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { host: 'http://myfaro.cfapps.io/'}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.mailgun.org',
port: 587,
authentication: 'plain',
#domain: 'sandboxe3e6f1cfc3d34efc8dba23c1a1eaff8b.mailgun.org',
domain: 'mg.myfaro.be',
#user_name: 'postmaster#sandboxe3e6f1cfc3d34efc8dba23c1a1eaff8b.mailgun.org',
user_name: 'postmaster#mg.myfaro.be',
#password: '25c695256391ca3e9f6c6bb1dd9f622f'
password: 'f1d6d58994362f084cc2ecac0e46256c'
}
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
config.i18n.available_locales = [:en,:nl,:fr,:de]
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
end
I got an answer from the Pivotal support team.
Pivotal Web Services' Apps Manager uses the /cloudfoundryapplication endpoint as the root for Spring Boot Actuator integrations. It calls this endpoint for an app when you view the app in the Apps Manager UI, regardless of whether you have configured Spring Boot Actuator endpoints for Apps Manager.
So for applications not using the Spring Boot Actuator endpoints these errors appear but only while using the Apps Manager GUI.
Its like Schrodingers Cat of the Light in the Fridge: if you don't look, the errors don't appear. I checked the logs via the CLI and indeed there are no errors at all.
Borrowing a line from an app's config/routes.rb:
match '/cloudfoundryapplication', to: proc { [200, {}, ['']] }, via: %i[get options]

Sitemap generators unable to generate sitemap

I have this website https://shopus.pk. I am unable to generate sitemaps using Sitemap generator tools. They just give error like "Error: 422 Unprocessable Entity" or just give me only 1 URL like following:-
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
</urlset>
I understand there is some problem relating to probably security settings of the website or server. But please someone help me identifying the problem. Thanks
BTW my website is being hosted by dreamhost. But I don't think dreamhost has anything to do with this.
I have tried https://www.xml-sitemaps.com/ , http://www.web-site-map.com/, http://www.check-domains.com/sitemap/index.php , https://websiteseochecker.com/html-sitemap-generator/ and many more.
Also I downloaded and tried A1 Sitemap Generator, gnucrawlandmap, SiteMapBuilder, HSEO Sitemap Generator and a few more free sitemap generating tools.
All of the above websites or tools wither give access error or return with just 1 or 2 URLs.
Since my website is built on Ruby on Rails my config file for production environment is below:-
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :error
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { host: "https://shopus.pk" }
# configure action_mailer
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {}
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.asset_host = 'https://shopus.pk'
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
And this is how my application controller looks like:-
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include SessionsHelper
include ApplicationHelper
private
# Confirms a logged-in user.
def logged_in_customer
unless logged_in?
store_location
redirect_to login_url
end
end
end
Let me know if you require anything else to solve this issue.
Ok looks like I have figured out the problem. But still not sure about it.
So after miserably failing with trying almost every site map generator I decided to create my own sitemap generator using Ruby Gems Nokogiri and Mechanize. But to my surprise whenever I would try to extract HTML code from my website the same error would show up "422 Unprocessable Entity". This was the exact error message which I was getting from a few Site map generators.
I removed "protect_from_forgery with: :exception" from Applications controller and the sitemap generators started working on my website.
But this wasn't right because "protect_from_forgery with: :exception" should be there. And I have 2 other websites with "protect_from_forgery with: :exception" included in the Application controllers. Sitemap Generators don't show any problem working with these 2 websites.
The only difference between my first website and the other 2 was that my first website was using ajax and the other 2 were simple. So i finally I figured out that when I remove the format.js line from
respond_to do |format|
format.js
format.html
end
code block from my index action in the main controller, things would start working. Later I realized that I should have written the respond_to code with format.js below format.html like this
respond_to do |format|
format.html
format.js
end
After this I changed all respond_to code in every action of all controllers with format.html above format.js
Everything is working fine now.
However I am still confused and not sure if my identification of the cause of problem is right? I am still a novice programmer. Also I fail to understand why the order of format.html and format.js matter in this case.
I am open to all suggestions and a little more insight into the problem.

Why would logout using devise + omniauth + google-oauth2 + rails work in dev but not in prod

The logout feature in my Rails application appears to be working when I run the app locally using localhost:3000; however, when I logout on the production server it is directing me to http://example.com/users/logout and then when I go to http://example.com I am still logged in.
I pushed all my changes up to the git repo and both dev / prod are both running the same source code. I am not sure why the prod box isn't logging the user out when they click the logout link.
development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
production.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# General Settings
config.app_domain = 'example.io'
# Email
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { host: config.app_domain }
config.action_mailer.smtp_settings = {
address: 'smtp.example.com',
port: '587',
enable_starttls_auto: true,
user_name: 'foo',
password: ':)',
authentication: :plain,
domain: 'example.com'
}
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
The logout behavior appears to be working now. I put //= require jquery_ujs below //= require jquery in the application.js file and now I am able to logout on the prod box. Thanks for the help guys.

rails custom_configuration gem produces empty orderedoptions

Ruby 2.1.5
Rails 4.0.13
Using the custom_configuration gem, I get unexpected results.
config/environments/development.rb
JumboSIP::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
module Devise
module LdapAdapter
def self.valid_credentials?(login, password)
return true
end
end
end
config.cache_store = :memory_store
config.log_level = :debug
config.assets.compile = true
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
[..etc]
# ------------------------------------
# Application-specific configuration
# ------------------------------------
# use active directory auythentication (only for production)
config.x.use_ad_auth = false
# Enable to create cockpit cache files
config.x.cockpit_cache_enabled = false
config/initializers/scheduler.rb
if Rails.configuration.x.cockpit_cache_enabled
Rails.logger.info 'Initializing Cockpit Cache Scheduler'
puts 'Initializing Cockpit Cache Scheduler'
The code in the if is reached while it should not.
Debug inspection shows that
Rails.configuration.x.cockpit_cache_enabled evaluates to Empty ActiveSupport:OrderedOptions.
Rails.configuration.x is of type CustomConfiguration::Configuration
I checked I am actually in development environment.
Any clue as to why this happens? Any conflicts with other gems?
If I uses orderedoptions outside this gem, behaviour is as expected
It's two months delayed, but I ran into the same issue. The custom_configuration gem expects the options to be namespaced under another hash. Instead of:
config.x.cockpit_cache_enabled = false
try:
config.x.cockpit.cache_enabled = false
Now you should be able to access the value with:
Rails.configuration.x.cockpit.cache_enabled

Extra directory prepended to my routes in production

My rails application works fine locally, and seems to deploy normally. The root route brings you to my welcome splash page. I have a link on that page to the index for my organizations model, generated by the following code:
<%= link_to("Organizations", organizations_path, :class => "button_blue") %>
When I try to click that link on the production server, hosted by a2 hosting, I get the following error:
Started GET "/database/organizations.shtml" for 11.222.33.444 at Sat Oct 05 00:10:35 -0400 2013
ActionController::RoutingError (No route matches [GET] "/database/organizations.shtml"):
actionpack (3.2.13) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
...
Why is it trying to get "/database/organizations" instead of "/organizations" like it does in development? The url in the address bar reads "http://database.mysite.com/organizations". Does it have something to do with the fact that the site is located at the subdomain database.mysite.com? How do I get around this, since I can't use the primary domain for my rails app?
For what it's worth, here's what I get when I run
RAILS_ENV=production bundle exec rake routes | grep organization
on the server:
organizations GET /organizations(.:format) organizations#index
POST /organizations(.:format) organizations#create
new_organization GET /organizations/new(.:format) organizations#new
edit_organization GET /organizations/:id/edit(.:format) organizations#edit
organization GET /organizations/:id(.:format) organizations#show
PUT /organizations/:id(.:format) organizations#update
DELETE /organizations/:id(.:format) organizations#destroy
Here is my routes.rb:
MyApp::Application.routes.draw do
root :to => 'application#index'
resources :grantmakers, :grant_records, :events, :organizations
end
Here is my config/environments/production.rb:
MyApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
And here is my application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery
def index
end
before_filter :basic_http_authentication
private
def basic_http_authentication
if Rails.env.production?
authenticate_or_request_with_http_basic do |username, password|
username == '---' && password == '---'
end
end
end
end
Thanks very much for your help.
Thanks to #phoet, I finally identified the problem and found a solution.
My Apache server was rewriting the URLs for some reason that I still don't understand. I think it might have to do with the way A2 hosting allows you to set up subdomains. In any case, adding the following line to the end of the .htaccess file in the subdomain's root directory solved the problem:
RewriteEngine Off
This simply disables all rewriting: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriteengine

Resources