Alexander Munck Alexander Munck - 1 year ago 97
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"+ "" would be output as "hello"
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: "//{youtube_id}")

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<br>
<p><iframe src="//"></iframe></p>

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 Source

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}\/watch\?v=\w*)/)
  output = ""
  output += "<p>#{text}</p>" unless text.empty?
  output += "<iframe src='#{link}</iframe>'" unless link.empty?

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}\/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

def embed_code(string)
  code = string.split("v=").last
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download