Sheldon
Sheldon

Reputation: 10077

How should I implement my Ruby code in Rails?

I have small piece of ruby code that fetches news from a website that doesn't provide the facility itself. I would like to display the results in a view but I'm not sure where I should store the logic for the code i.e. helper, model (or lib)?

Looking for some guidance on the pros/cons of each and which choice is the most logical.

require 'nokogiri'
require 'open-uri'
require 'json'

news = []
domain      = ""
councilnews = Nokogiri::HTML(open(domain + ""))
councilnews.css('p.newsTitle').select do |article| 

    headline = article.text
    link     = domain + article.css('a').attribute('href').to_s
    content  = article.next_element.text 
    newsItem = {headline: headline, link: link, content: content}


    news.push(newsItem.to_json)

end

Upvotes: 0

Views: 58

Answers (1)

nightire
nightire

Reputation: 1371

IMO, If you don't intent to store these fetched data permanently, just save these code as a lib, invoked by controller so the view can access its results.

Otherwise, you may consider to use them as a "service" for model using, that you maybe need to build a model to construct those data's structure and store them in database for further use.

It doesn't matter where you put those code in, a /lib directory? a app/service directory? both fine, this's just a convention. What really matters is how those code should be invoked and what role those code played in your business logic?

Upvotes: 2

Related Questions