2

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

VegaStudios
  • 378
  • 1
  • 4
  • 22
  • 1
    Are you running the code in console? From the error, it looks like the method was added after you enter the console, try exit console and go back. – Vibol Sep 03 '19 at 04:05
  • 1
    I'm running it from the `create` action of the `StoreController`. I call the method inside the `create` action like so, `@store = ::Store::CreateService.new(current_user, store_params).execute` – VegaStudios Sep 03 '19 at 04:07
  • Don't find anything wrong with the code, please make sure you save the file. – Vibol Sep 03 '19 at 04:11
  • Thanks @Coco, I've doubled checked that the file is saved. – VegaStudios Sep 03 '19 at 04:21
  • 1
    Fix the syntax in service, include the method in CreateService – Bijendra Sep 03 '19 at 04:40
  • i suggest you should move your account_id , creation logic in model, and instead of writing **@store** , you should use attr to define objects , which will give you freedom from writing @store everywhere and just use **store** to access that object. good luck. – Ashok Damaniya Sep 03 '19 at 04:53

1 Answers1

7

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.

fylooi
  • 3,840
  • 14
  • 24