1

I have a db that has a column src_url, that contains full urls to web resources. Currently I use

<%= link_to "source", @article.src_url %>

to display it.

What I want to do is to display first 2 or 3 domain levels instead of "Source" (so for example "www.example.com" or "example.org").

I'm fairly new to ruby on rails, so having to figure out about everything on the go, this one I was stuck on for a while.

1 Answer 1

1

You can use the URI module:

uri = URI(@article.src_url)
uri.host
#=> "example.com"

This module is already included in Rails, so you should not include it manually.

Sign up to request clarification or add additional context in comments.

3 Comments

Not sure how to use this. Do I add this to one of .html.erb files in view or somewhere else?
Currently my project is fairly simple: it consists of sqlite db, 1 controller and a bunch of view files. It essentially begun with tutorial on guides.rubyonrails.org and from there I kept adding and changing stuff. I'm still only figuring out what goes where, so I'm a little lost every now and then.
It worked, thanks! Used <%= link_to URI(@article.src_url).host, @article.src_url %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.