Alexander Munck Alexander Munck - 3 months ago 13
Ruby Question

Distinguisihing normal text from a youtube link Ruby on Rails

Hello all i am making a facebook clone using ruby on rails,
I got a post form where i can write text and add a youtube link if i want and it works. However writing a text like "hello world"+ "www.youtube.com/etc" would be output as "hello worldwww.youtube.com/..."
If i would just write "hello world" it would make a iframe for a youtube video which isnt correct either.

My application helper

def embed(youtube_url)
youtube_id = youtube_url.split("=").last
content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{youtube_id}")
end


In my view

<p><%= embed post.content %></p>


My question is how could i make an if else statement to see if a youtube url is present, if so show the video but hav it on its own "block" and the text separate, if no video dont display the iframe and just the normal text that i write.

Current output:

<div class="post-content">
Hello World this is a sample text
https://www.youtube.com/watch?v=X3dVpRAmq_8<br>
<p><iframe src="//www.youtube.com/embed/X3dVpRAmq_8"></iframe></p>
</div>


I want to have it show like

This is a sample text



But a if /else statement, if there is a youtube video present add it but in its own tag, if no video is present just show the normal content i add

Answer

I can think of 2 ways to approach this problem. Implement a presenter or create a helper method.

For the second approach, you would pass the input as a parameter to the helper method. You can determine what kind of content you're dealing with by using a regex to check for the existence of a you tube link. Here's a quick example

def my_helper_method(string)
  text, link = string.partition(/(w{3}.youtube.com\/watch\?v=\w*)/)
  output = ""
  output += "<p>#{text}</p>" unless text.empty?
  output += "<iframe src='#{link}</iframe>'" unless link.empty?
  output
end

Rubular is a useful site for experimenting with regexes.

Here's how you could use it with content_tag

def test_helper(string)
  text, link = string.partition(/(https:\/\/w{3}.youtube.com\/watch\?v=\w*)/)
  text_html = text.empty? ? nil : content_tag(:p, text)
  iframe = link.empty? ? nil : content_tag(:iframe, nil, {src: embed_code(link)} )
  text_html + iframe
end

def embed_code(string)
  code = string.split("v=").last
  "https://www.youtube.com/embed/#{code}"
end
Comments