Sam
Sam

Reputation: 1643

How to get content value out of meta tag in ruby on rails?

I have this list of meta tags in my view HTML (after the page loads). The tag is generated dynamically,

@meta = "\n  <meta content=\content1\">\n  <meta content=\content2\">\n  <meta content='content2\">\n  ....... <meta content=\"2019/01/10 09:59:59 +0900\" name=\"r_end\">\n \n"

I wanted to fetch the value 2019/01/10 09:59:59 +0900 inside content i.e.<meta content=\"2019/01/10 09:59:59 +0900\" name=\"r_end\">. Is there a way to get the value of the content from the meta tag.

Upvotes: 1

Views: 977

Answers (2)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

How about a using simple regular expression to capture the value using String#scan.

This will work only if the name of metatag doesn't change

@meta = "\n  <meta content=\content1\">\n  <meta content=\content2\">\n  <meta content='content2\">\n  ....... <meta content=\"2019/01/10 09:59:59 +0900\" name=\"r_end\">\n \n"

@meta.scan(/content=\"(.*)\" name=\"r_end\"/) 
#=> [["2019/01/10 09:59:59 +0900"]]

Explanation:

The above code will capture the value of content with metatag name="r_end"

If you think there might be some other HTML elements with name="r_end" you might need to add some other identifier in the regex

Upvotes: 0

Stefan
Stefan

Reputation: 114158

Given a @meta variable containing some HTML snippet as a string:

@meta = <<-HTML
  <meta name="foo" content="content1">
  <meta name="bar" content="content2">
  <meta content="2019/01/10 09:59:59 +0900" name="r_end">
HTML

You can use Nokogiri to parse it:

require 'nokogiri'
doc = Nokogiri::HTML::DocumentFragment.parse(@meta)
doc.at_css('meta[name="r_end"]')['content']
#=> "2019/01/10 09:59:59 +0900"

at_css returns the first element matching the given CSS selector and [] returns the value for the given attribute.

Upvotes: 3

Related Questions