Sauce McBoss
Sauce McBoss

Reputation: 6947

Rails: Where should I put this method?

I have multiple models in my application for different types of content, and I frequently need to get whichever one was most recently published. At the moment, I'm using helper_method :latest_content in my application controller.

Is this the best place to put this method? If so, how should I write rspec tests for it?

Upvotes: 1

Views: 57

Answers (1)

Hspazio
Hspazio

Reputation: 73

Sounds like you have a common functionality across multiple models. Rails has concerns which allow you to do that.

# app/models/concerns/searchable.rb
module Searchable
  extend ActiveSupport::Concern

  module ClassMethods
    def last_content
      # ... here whatever is the content of :last_content
    end
  end
end 


# app/models/model_x.rb
class ModelX < ActiveRecord::Base
  include Searchable
  ...
end

# app/models/model_y.rb
class ModelY < ActiveRecord::Base
  include Searchable
  ...
end

Upvotes: 3

Related Questions