how to create dynamic routes and helpers in rails3 - ruby-on-rails

i have a task to create mapping of different urls at run time .
In the application i have a GUI interface which displays list of routes from routes.rb file.
User has the ability to change that url to some different name from the interface
eg. (abc/mno) --user can change them to --(hello)
so if user type /hello in the browser request is redirected to /abc/mno
i have to store those mapped routes in a database.
how to add a dynamic mapped route to already defined routes(routes.rb) while creating a new record in database
how to add routes from the database while loading routes.rb file.
i am not able to figure out how to extend the default router so that it can include routes from the database ..

I don't have a complete solution for you, but you can start with two approaches:
Use custom URL constraint: Dynamic URL -> Controller mapping for routes in Rails
Use Rack middleware: Dynamic Rails routing based on database

If you don't want to use rack middleware, you can use constraints. Hopefully, your dynamic routes are scoped to something, like "/abc/anything-after-here-can-be-dynamic", as opposed to straight off the root...
So, lets say you wanted dynamic routes based upon User's first name, then you would do the following:
#config/routes.rb
match '/abc/:route' => "abc#dynamicroute", :contraints => DynamicRouteConstraint.new
#lib/dynamic_route_constraint.rb
class DynamicRouteConstraint < Struct.new
def matches?(request)
User.find_by_first_name(request.params[:route]).present?
end
end
#app/controllers/abc_controller.rb
class AbcController < ApplicationController
def dynamicroute
#user = User.find_by_first_name(params[:route])
#render or redirect, however you wish
end
end

Related

How to implement URL shortener with rails with two separate hostname?

Let's say I have a domain, foobargoo.com, and I recently registered fbg.co so that I can add Url shortener to. I may have a lot of requests which has a route foobargoo.com/requests/:id which may end up be more than 100 character, and I would like to use something like fbg.co/TxFj4 (which provides > 900 million strings) and redirect to the specific ID.
I am wondering if I can do it from within one rails codebase in the routes.rb, or do I have to add a new repo just to do it?
It seems okay to have that in one code base. You certainly don't need to create separate project, but you may want to to speed up the redirection (for example by having light-weight Sinatra project instead of Rails).
In your routes.rb you can add shortened routes like this:
constraints(host: 'fbg.co') do
get ':id', to: 'shortener#redirect'
end
Then use a simple action to handle redirects:
# shortener_controller.rb
class ShortenerController < ApplicationController
def redirect
redirect_to ShortLink.find_by_hash(params[:id]).url
end
end
Of course, you need a model which will store short URLs and map them to full URLs as well:
class ShortLink
# Migration for its creation is something like:
# t.string :hash
# t.string :path
def url
"foobargoo.com/#{path}"
end
end

change routing name dynamically

I have to modify the routes file in order to have SEO improvement.
This is my context, a rails backend generate a JSON feed with the route's name in, I have to read it and change the default name.
For example, I have this:
get '/people' => 'people#show', as: :people
and I'd like to change /people in some value read from my JSON feed.
I created a class to get the JSON object in my app
class JSONDatabase
def initialize(kind_of_site)
#kind_of_site = kind_of_site
end
def fetch_database_remote(url)
JSON.parse(open(url).read)
end
end
but how can i access it in routes file?
Thank you
You don't necessarily need to modify your application's routes. What you can do is define a wild card route that leads to a unique controller where you read the updated route. This approach is kind of hackish but gives you the unlimited routes you need without modifying the routes.
Your config/routes.rb file would look something like this:
resources :defined_models
root to: 'controller#action'
# At last we define the wildcard route
get '/:route' => 'routing_controller#routing_action'
Then, at this routing action we can do the job of seeing if this route (now defined in the params[:route] variable) corresponds to the modified one. Just remember to redirect to a 404 if the route given is not defined, since with this approach you loose the Rails default way of dealing with undefined routes.

Add new view to a controller in Rails

I have a controller, clients_controller, with corresponding index, show, edit, delete, new & form views. Is there a way to create a new view like clients/prospects.html.erb that acts the same way as clients/index.html.erb, except is routed at clients/prospects/?
I've tried this:
match '/clients/prospects' => 'clients#prospects'
And some other things in routes.rb, but of course get the error "Couldn't find Client with id=prospects".
The goal here is basically to have a prospects view and a clients view, and by simply switching the hidden field to a 1, it (in the user's mind) turns a prospect into a client (it's a CRM-like app).
There's a couple of things you need to do. First you need to put the your custom route before any generic route. Otherwise Rails assumes the word "prospects" is an id for the show action. Example:
get '/clients/prospects' => 'clients#prospects' # or match for older Rails versions
resources :clients
Also you need to copy / paste the index method in your ClientsController and name it prospects. Example:
class ClientsController < ApplicationController
def index
#clients = Client.where(prospect: false)
end
def prospects
#prospects = Client.where(prospect: true)
end
end
Lastly, you need to copy the index.html.erb view and name the copy prospects.html.erb. In the example above you would have to work with the #prospects instance variable.
Create a new action in clients controller named prospects. And then define a collection route in routes.rb for it as either resource full way. Or u directly use match as you were doing.
What you're doing is not wrong (although I'd change match to get, otherwise POST and DELETE requests to that url will also render your prospects view). Presumably you have
resources :clients
in your routes file? If so, what you have will probably work if you just move the line you quoted above the resources declaration -- the problem is that /clients/prospects matches the show route for the clients resource, so if it's defined first then that's the route that gets matched.
However, there's a more idiomatic way to define this route
resources :clients do
collection do
get :prospects
end
end
See Rails Routing documentation for more
Also see migu's answer for what else needs to be done once the url is being routed correctly (though there are other things you can do -- if you the two views are similar enough, you can reuse the view template, for example).

Alias route's name

I need to have one path accessible through multiple names. In my routes.rb I did
get '/route' => 'controller#edit', :as => 'name_a'
get '/route' => 'controller#edit', :as => 'name_b'
This works nicely but loads the routes table for nothing. From my understanding of the documentation, :as defines a helper method when called.
So I went to my ApplicationController and added
alias_method :name_b, :name_a
and I removed the second line from routes.rb
but that fails with Uncaught exception: undefined method name_a for class ApplicationController
is there any proper way of having two names for a single path?
=================EDIT====================
Elaboration:
I use Devise gem to manage session, registration, locking, etc. of 2 kinds of users, let's call them Admin and Guest. The gem is very well put but it asks for definitive route names to behave properly.
In my case, as far as devise is concerned, only the registration process is different so I'm trying to build a structure which looks as follow:
app
controllers
users
admin
registration_controller.rb
guest
registration_controller.rb
session_controller.rb
password_controller.rb
registration_controller.rb
the Admin and Guest controllers inherit from the above registration_controller which inherit's from Devise.
Now, to work properly, Devise needs for instance the names guest_user_password and admin_user_password to create or delete password retrievals. In my case, both are under the same path so I want both names to redirect to the same 'users/password' controller.
More important, and that's why I really wanted the alaising. Is that my views should not care whether it is dealing with Admin and Guest routes when redirecting to password retrieval controller. Both are users so I want to use user_password for both.
Hence my question. :)
Also note that as I wrote it, things works. I'm just trying to get the 'most elegant way' of writing it.
How about putting the alias in your ApplicationController?
class ApplicationController < ActionController::Base
alias_method :route_new, :route_old
helper_method :route_new
Remember that it's new name first, then old name.
The helper_method call is in order to use these in your views and not just controllers.
If you like, you can then place this in an included module called something like RouteAliases
You can add something like this to your routes.rb:
Rails.application.routes.draw do
...
Rails.application.routes.named_routes.tap do |named_routes|
named_routes['new_name'] = named_routes['real_name']
end
end
This will create new_name_path and new_name_url helpers. I have tested this with Rails 5.0.6.

Rails 3.1 Change the URL in a Controller

How do I Change the URL for the view in the controller.
In my controller I generate an ID which I want to display
in the URL of the browser when the view is rendered.
For example, when I enter / in my browser, it should redirect me
to /test/1. The ID is generated randomly by the controller.
So when I access / the 2nd time it could redirect me to /test/3.
I tried to do a match route in my routes.rb file.
But I couldn't find a solution.
routes.rb
get 'test/run'
root to: 'test#run'
match '/test/:id', to: 'test#run'
How about that:
class TestController
def show
...
end
def run
redirect_to Test.random
end
end
Of course, you have to write random scope for your Test model.
You may find helpful this question also - Random record in ActiveRecord
P.S. I'm not sure that the Test is a good name for your model. It could be already used by ruby or rails.

Resources