Remove http of url for displaying website addresses in rails - ruby-on-rails

In my rails app, each supplier has a website address which is displayed on their supplier show page (value is #supplier.website).
If the website url begins with http:// I'd like to remove this from the view page i.e. rather than displaying http://www.google.com it would just display www.google.com (but the actual #supplier.website will remain unchanged).
Hope that makes sense, and that someone can help...Thanks

You can do that with a URI parse.
uri = URI.parse 'http://google.com/whatever'
uri.host #=> 'google.com'
uri.path #=> '/whatever'
Best to make a helper
def website_link_text(uri)
URI.parse(uri).host
end
And then in the view:
<%= link_to website_link_text(#supplier.website), #supplier.website %>

Related

Rails Render Index with URL Parameters

At my work, we are in the middle of breaking up our Rails monolith. We are currently serving our react app through the asset pipeline. I am implementing JWT for authentication. I am trying to pass the token in the url without using sessions/cookies as part of an admin impersonating a user.
class ReactPagesController < ApplicationController
def index
render :index #this will open up the react app
end
end
Is it possible to render a view and pass along parameters in the url?
I want this to open up the index page with url parameter (i.e. localhost:4000/users?jwt=abc.def.ghi
I've tried doing something like render :index, jwt: abc.def.ghi, but that doesn't work. Is the only way to do this via redirect_to?
You are actually defining a redirection:
You want to go to localhost:4000/users
The page display the index page, and URL becomes localhost:4000/users?id=123
For the normal webpage, changing URL will make the browser redirect. As you can see the result when executing this JS in the Chrome Console:
window.location.href = "google.com"
the browser will redirect you to google.com
So, for a Rails's application, you should do a redirection by redirect_to to achieve the current needs.
However, if you really want to change the URL without redirection, you can do it via Javascript. Just use window.history to change your URL
Your controller:
# app/controllers/users_controller.rb
def index
#desired_id = 123
end
and your view
<%-# app/views/users/index.html.erb %>
<!-- rest of HTML -->
<script>
window.history.pushState("", "", "?id=<%= j #desired_id %>");
</script>
you can use redirect_to
redirect_to users_url, id: 5
will get you to /users?id=5
I don't think so, render is for rending the view and has nothing to do with the setting the url.
ruby docs

Catching 301 redirection in rails

There are certain cases in which we are doing a 301 redirect for pages from the controller. redirect_to product_show_path(updated_id), status: :moved_permanently. These redirections are working but we want to setup a custom meta tag when user is landing on a page by a 301 redirect. Is there any way to know it globally that is set it in the application.html.erb file?
Use query string parameters to send additional data with a GET request (a 301 Redirect is always a GET request).
redirect_to product_show_path(updated_id, redirected_from: URI.encode(request.original_url))
This creates a param in the params hash just like any other:
<%= if params[:redirected_from].present? %>
You where redirected from <%= URI.decode(params[:redirected_from]) %>
<% end %>
This unlike the HTTP_REFERER header works in all browsers.

Making a instance variable a clickable direct link

In my app a user can create a post that has a link to a given website.
Example..
post.title -> I use this site to research topics.
post.link -> google.com
In post.show I would like to have a direct link to google.com
I try to do it simply with this:
<p><%= link_to #post.link%></p>
I need the link to route the user to google.com. However, it routes the user to
/topics/12/posts/www.google.com
That's because you're missing http:// on the Post's link attribute. When saving the record, you could check that the link string starts with http:// or https:// and if it doesn't, prepend the string accordingly.
Update:
Add a callback to your Post model:
before_save :prepend_link
Add a private method to your Post model:
private
def prepend_link
self.link = "http://#{link}" unless link.starts_with?('http://', 'https://')
end
Use this in your view:
<%= link_to #post.link, #post.link %>

Missing character from link Ruby on Rails

I have a Link resource. In my view, I have a series of links that people can click to open another web page:
<%= link_to link.description, "http://#{link.url}", :target => '_blank' %>
If the value of #{link.url} is www.google.com, the link works fine. However, if the value of #{link.url} is http://www.google.com and I click it, it will go to the address http//www.google.com <--- notice it's missing a : after http. Can someone help me remedy this?
Thanks!
How about you add a helper method that checks to see if link.url contains 'http://' or not.
You could use something like this:
def link_formatter(url)
prefix = "http://"
url.include?(prefix)? url : prefix + url
end
That will check to see if link.url contains "http://", if it doesn't it will return the proper format for your url, if it does, it will just return link.url as is.

Detect links to site’s videos and show title

I have a problem.
I have a Video and Comment model.
If the user inserted the link to video into the comment, it is link to replace with the title from video.
How should I write a method?
def to_show_title_instead_of_the_link
body.gsub!(%r{(videos)\/([0-9])}) {|link| link_to link)}
end
We input:
http://localhost:3000/videos/1
We receive:
test video
It sounds like you want to take a given URL on your site, and find the associated parameters for that route. This will let you get the id for the video in a clean, DRY way (without using a regex that might break later if your route changes). This will then let you look up the model instance and fetch its title field. The Rails method for this task is Rails.application.routes.recognize_path, which returns a hash with the action, controller, and path parameters.
In your view:
# app\views\comments\show.html.erb
# ...
<div class='comment-text'>
replace_video_url_with_anchor_tag_and_title(comment.text)
</div>
# ...
And here is the helper method:
# app\helpers\comments_helper.rb
def replace_video_url_with_anchor_tag_and_title(comment_text)
# assuming links will end with a period, comma, exclamation point, or white space
# this will match all links on your site
# the part in parentheses are relative paths on your site
# \w matches alphanumeric characters and underscores. we also need forward slashes
regex = %r{http://your-cool-site.com(/[\w/]+)[\.,!\s]?}
comment_text.gsub(regex) do |matched|
# $1 gives us the portion of the regex captured by the parentheses
params = Rails.application.routes.recognize_path $1
# if the link we found was a video link, replaced matched string with
# an anchor tag to the video, with the video title as the link text
if params[:controller] == 'video' && params[:action] == 'show'
video = Video.find params[:id]
link_to video.title, video_path(video)
# otherwise just return the string without any modifications
else
matched
end
end
end
I didn't know how to do this off the top of my head, but this is how I figured it out:
1) Google rails reverse route, and the first result was this stackoverflow question: Reverse rails routing: find the the action name from the URL. The answer mentions ActionController::Routing::Routes.recognize_path. I fired up rails console and tried this out, however it is deprecated, and didn't actually work.
2) I then google rails recognize_path. The first search result was the docs, which were not very helpful. The third search result was How do you use ActionDispatch::Routing::RouteSet recognize_path?, whose second solution actually worked.
3) Of course, I then had to go refresh my understanding of Ruby regex syntax and gsub!, and test out the regex I wrote above =)
I did refactoring code and used a gem rinku
def links_in_body(text)
auto_link(text) do |url|
video_id = url.match(/\Ahttps?:\/\/#{request.host_with_port}\/videos\/(\d+)\z/)
if video_id.present?
Video.find(video_id[1]).title
else
truncate(url, length: AppConfig.truncate.length)
end
end
end

Resources