ruby-on-railsrubyservice-object

Rails using private and protected methods in a Service object


I'm trying to move some business logic out of one of my controllers, StoreController and into a new Store::CreateService service object. Learning about services recently, it doesn't seem to be much of an established pattern for implementing them. I'm running into an error trying to call a protected method. I can obviously move the logic from those protected methods directly into execute but my understanding was that this should be okay to Rails.

undefined local variable or method `find_and_set_account_id' for #<Store::CreateService:0x00007f832f8928f8>

Here is the Service object

module Store
  class CreateService < BaseService

    def initialize(user, params)
      @current_user, @params = user, params.dup
    end

    def execute

      @store = Store.new(params)

      @store.creator = current_user

      find_and_set_account_id

      if @store.save
        # Make sure that the user is allowed to use the specified visibility level
        @store.members.create(
          role: "owner",
          user: current_user
        )
      end

      after_create_actions if @store.persisted?

      @store
    end
  end

  protected

    def after_create_actions
      event_service.create_store(@store, current_user)
    end

    def find_and_set_account_id
      loop do
        @store.account_id = SecureRandom.random_number(10**7)
        break unless Store.where(account_id: account_id).exists?
      end
    end
end


Solution

  • You have an extra end after def execute..end. That end closes the CreateService class. This means your protected methods are defined on the Store module.

    Hence the missing method.