0

I have been using RoR for the past two weeks, and I'm not sure where to put a piece of logic.

I have two models: Site and Post. The Post model has many relationships with other models that represent all sort of metrics, for example: InteractionMetrics. The interaction metrics are calculated as soon as a post is saved, and for the actual gathering of the data I use a third-party service. I've created an API wrapper (SDK) for the interaction with the third-party service, and in the InteractionMetrics I have:

class InteractionMetrics < ApplicationRecord

  def gather_interactions
    client = XxxApi.new <url_of_post>
    data = client.get_interactions
    # Save data here
  end
end

Now, I'm not sure if that's the correct place to put this logic, and if it's not, where should I put it instead?

Btw, I know I'm not supposed to ask more than one question, but I'm not sure how to get the post that this belongs to.

  • 3
    I would say answer would be opinion based. For example you can check for "Service objects" in Rails – Fabio Oct 24 '19 at 22:27
  • 1
    You might want to have a look at *concerns* if you want to share the logic among different classes or modules. https://api.rubyonrails.org/classes/ActiveSupport/Concern.html – a.barbieri Oct 24 '19 at 22:32
  • I tend to place logic like this in my lib folder. – Verty00 Oct 24 '19 at 23:47

1 Answers1

0
# app/models/interaction_metrics.rb
require 'my_resource'

class InteractionMetrics < ApplicationRecord
  def gather_interactions
    MyResource.get_interactions
  end
end

Then put your ruby code on /lib folder

# lib/my_resource.rb
class MyResource
  URL = <url_of_post>
  def self.get_interactions
    client = XxxApi.new(URL)
    client.get_interactions
  end
end

Rails: /app vs /lib folder

Danilo Cândido
  • 408
  • 1
  • 5
  • 18
  • The modern Rails practice is to use `/app/lib`, not `/lib`. [Ref](https://stackoverflow.com/a/40019108/3784008) – anothermh Oct 25 '19 at 16:34