Rails localize path without locale param for certain url - ruby-on-rails

I am fairly new to Rails and in the process of building localization for my rails project. I have followed Rails i18n guide and is able to use localized path to different language version of the site.
My routes.rb looks like the following:
scope "/:locale" do
# blah
end
namespace :admin do
# admin blah
end
However because I have used default_url_options in application controller as suggested in Rails guide, the path generated by URL helper will also contain locale params. When I create link to my admin root localhost:3000/admin?locale=en, I will get an error saying "admin" is not a valid locale
Is there a way to make exception for the generated url to not including the locale parameter?

I finally figured out a workaround for this. All I needed to do is to place the admin namespace routing before the scoped routes, such as
namespace :admin do
# admin blah
end
scope "/:locale" do
# blah
end
After I set it up like above, the error went away.

Related

Change default url from Active Storage

Can we change the default 'permanent' url create from active storage to redirect to S3. Is something like rails/active_storage/representations/. I don't like the framework name in the url.
Thanks
UPDATE:
Recently, there was an addition which makes the route prefix configurable in Rails 6: https://guides.rubyonrails.org/6_0_release_notes.html#active-storage-notable-changes
It's just a matter of configuration:
Rails.application.configure do
config.active_storage.routes_prefix = '/whereever'
end
Unfortunately, the url is defined in ActiveStorage routes.rb without easy means to change:
get "/rails/active_storage/blobs/:signed_id/*filename" =>
"active_storage/blobs#show", as: :rails_service_blob
get "/rails/active_storage/representations/:signed_blob_id/:variation_key/*filename" =>
"active_storage/representations#show", as: :rails_blob_representation
One solution starting point I can think of is defining your own Routes in addition and overriding the "rails_blob_representation_path" or similar
get "/my_uploads/:signed_blob_id/:variation_key/*filename" =>
"active_storage/representations#show", as: :my_upload
and then overriding the path in a helper file and include the helper into the Named Helpers:
How to override routes path helper in rails?
module CustomUrlHelper
def rails_blob_representation(*args)
my_upload(*args)
end
end
# initializer etc.
Rails.application.routes.named_routes.url_helpers_module.send(:include, CustomUrlHelper)
The solution might need some adjustments though, I didn't tested it.

Auto-generate routes for scaffolded controller in Rails 4?

I'm trying to get a quick-and-dirty Ajax UI going for an app that already has its data model well in hand - it's basically been managed via rails console so far. Anyway, I thought I would start by auto-generating the missing controller logic that you would get from a rails g scaffold, only instead with rails g scaffold_controller for an existing controller.
It created the controller, and the views, and the assets.. but it didn't touch the routes at all! It didn't even try, didn't say "warning: routes.rb has been modified, not changing" or anything like that, and there's no mention of routes at all in the help output of rails g scaffold_controller.
So how do I say "Just give me the normal routes you would have given me if I started from scratch, please!"?
If I understand the question:
Please, open the config/routes.rb file, and inside the block (routes.draw) add the resources method with the table name (plural of model) as param. Like this:
MyApp::Application.routes.draw do
resources :products
... # rest of code
end
That define the routes for RESTful actions over products. You can read more here
At the console you can run: rake routes to see the available routes at your app.
Although this is asking about Rails 4 for long time ago, but with Rails 5, rails g scaffold_controller still won't auto-generate route, I did it with below monkey patch:
require 'rails/generators/rails/scaffold_controller/scaffold_controller_generator'
patcher = Module.new do
extend ActiveSupport::Concern
included do
hook_for :resource_route, required: true
end
end
Rails::Generators::ScaffoldControllerGenerator.send :include, patcher

How to protect rspec_api_documentation apitome route without a controller

I have a set of API documentation pages that I want to password protect using devise. The docs are generated using rspec_api_documentation. The gem uses rspec to execute the API methods and create html or json doc files. I'm generating json and using another gem, apitome, as a viewer.
This is all working beautifully and my api docs can be found at /api/docs, but I can't figure out how to require authentication to view the docs.
The docs are viewed through apitome so it using rails. There isn't a route in routes.rb, but the apitom initializer mounts the docs.
From apitom initializer:
# This determines where the Apitome routes will be mounted. Changing this to "/api/documentation" for instance would
# allow you to browse to http://localhost:3000/api/documentation to see your api documentation. Set to nil and mount
# it yourself if you need to.
config.mount_at = "/api/docs"
https://github.com/zipmark/rspec_api_documentation
https://github.com/modeset/apitome
I found this How-to that is supposed to make every page on the site require authenication, but I'm still able to hit the docs url without signing in.
#https://github.com/plataformatec/devise/wiki/How-To:-Require-authentication-for-all-pages
Thanks for any help.
You can take control of Apitome controller and request auhentication.
configure apitome to not mount itself by setting mount_at to nil
write your controller ApidocsController extending Apitome::DocsController
add before_filter :authenticate_user! in your controller
add a route to your controller: get '/api/docs', to: 'apidocs#index'
Controller implementatin would go like this:
class ApidocsController < Apitome::DocsController
before_filter :authenticate_user!
end
If you have Devise already configured (for example if you already use ActiveAdmin) you can share the same authenticated session.
You have to disable the default mounting of Apitome:
# config/initializers/apitome.rb
Apitome.setup do |config|
config.mount_at = nil
# ...
end
Since this will break links in Apitome, you have to add to your application.rb:
# config/application.rb
# ...
class Application < Rails::Application
config.after_initialize do
Apitome.configuration.mount_at = '/docs'
end
# ...
end
Then force mount of the Apitome engine under Devise authenticated session:
# config/routes.rb
Rails.application.routes.draw do
# ...
authenticated :admin_user do
mount Apitome::Engine => '/docs'
end
# root_to ...
end
Now /docs is accessible only for already authenticated users.
PS: replace :admin_user (default for Active Admin) to :user or any other model name where Devise is configured.
I am using the cut down rails api, so did not have any views or devise and so no simple way to implement password protection. Accordingly I went for the following solution.
Apitome.setup do |config|
config.mount_at = nil
# ...
end
and in the routes.rb file:
mount Apitome::Engine => '/api/docs' unless Rails.env.production?
Finally, I just did a pdf of the api/docs page, and then sent the pdf to anyone what had a right to see the documentation. Obviously not suitable for a large user base, but works fine for a small one, e.g. within a company's IT group.
If anyone is using Raddocs, add mounted route inside authentication block as below:
authenticate :user do
mount Raddocs::App => "/docs"
end

Rails generate controller (under a namespace)

I want to add a controller and its routes entry under a namespace (api) for which I am proceeding with rails generate api/Users my_method, which creates the files and entries as follows:
create app/controllers/api/users_controller.rb
route get "users/my_method"
invoke erb
create app/views/api/users
create app/views/api/users/my_method.html.erb
Everything worked fine apart from the routes entry. What I am assuming is it should create the routes entry as well under the correct namespace or it shouldn't create it at all, or I am doing something wrong.On the other hand when going with scaffold way it does correctly.
Is it something which we need to do it manually?
Using ruby 2.0 and rails 4 for the application.
Type in terminal
rails generate scaffold Api::User username email
rake db:migrate
this is part of result
class Admin::ServicesController < ApplicationController
# GET /api/users
# GET /api/users.json
def index
#api_users = Api::User.all
end
To do generate and I think you will understand everything, don't forget see new app structure :-), Good luck, and solve your problem quickly as possible.
You can namespace your routes in your config/routes.rb like this
namespace :api do
resources :user
end

Remove Routes Specified in a Gem?

Is there a way to remove routes specified in a gem in Rails 3? The exception logger gem specifies routes which I don't want. I need to specify constraints on the routes like so:
scope :constraints => {:subdomain => 'secure', :protocol => 'https'} do
collection do
post :query
post :destroy_all
get :feed
end
end
Based on the Rails Engine docs, I thought I could create a monkey patch and add a routes file with no routes specified to the paths["config/routes"].paths Array but the file doesn't get added to ExceptionLogger::Engine.paths["config/routes"].paths
File: config/initializers/exception_logger_hacks.rb
ExceptionLogger::Engine.paths["config/routes"].paths.unshift(File.expand_path(File.join(File.dirname(__FILE__), "exception_logger_routes.rb")))
Am I way off base here? Maybe there is a better way of doing this?
It is possible to prevent Rails from loading the routes of a specific gem, this way none of the gem routes are added, so you will have to add the ones you want manually:
Add an initializer in application.rb like this:
class Application < Rails::Application
...
initializer "myinitializer", :after => "add_routing_paths" do |app|
app.routes_reloader.paths.delete_if{ |path| path.include?("NAME_OF_GEM_GOES_HERE") }
end
Here's one way that's worked for me.
It doesn't "remove" routes but lets you take control of where they match. You probably want every route requested to match something, even if it is a catch all 404 at the bottom.
Your application routes (MyApp/config/routes.rb) will be loaded first (unless you've modified the default load process). And routes matched first will take precedence.
So you could redefine the routes you want to block explicitely, or block them with a catch all route at the bottom of YourApp/config/routes.rb file.
Named routes, unfortunately, seem to follow ruby's "last definition wins" rule. So if the routes are named and your app or the engine uses those names, you need to define the routes both first (so yours match first), and last (so named routes point as you intended, not as the engine defines.)
To redefine the engine's routes after the engine adds them, create a file called something like
# config/named_routes_overrides.rb
Rails.application.routes.draw do
# put your named routes here, which you also included in config/routes.rb
end
# config/application.rb
class Application < Rails::Application
# ...
initializer 'add named route overrides' do |app|
app.routes_reloader.paths << File.expand_path('../named_routes_overrides.rb',__FILE__)
# this seems to cause these extra routes to be loaded last, so they will define named routes last.
end
end
You can test this routing sandwich in the console:
> Rails.application.routes.url_helpers.my_named_route_path
=> # before your fix, this will be the engine's named route, since it was defined last.
> Rails.application.routes.recognize_path("/route/you/want/to/stop/gem/from/controlling")
=> # before your fix, this will route to the controller and method you defined, rather than what the engine defined, because your route comes first.
After your fix, these calls should match each other.
(I posted this originally on the refinery gem google group here: https://groups.google.com/forum/?fromgroups#!topic/refinery-cms/N5F-Insm9co)

Resources