0

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

1 Answer 1

2

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?

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

2 Comments

Thanks for the quick answer. The only thing I will do with the result is display it in a view.
@Sheldon Ok, let controller invoke it to fetch data for views. Don't let view directly call it as a helper, it is not just a helper, it interacts with out-sourcing and should be considered as an extra action which belongs to controller level. More importantly it is better for testing.

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.