interactor-contracts icon indicating copy to clipboard operation
interactor-contracts copied to clipboard

`schema` on a class fails with "undefined method `key?' for #<ModelNameHere..."

Open zedtux opened this issue 4 years ago • 0 comments

Using this gem in a Rails project, I wrote the following:

class EnqueueMessagingJob
  include Interactor
  include Interactor::Contracts

  expects do
    required(:conversation).schema do
      required(:type).filled(included_in?: %w[email sms])
      # ...
    end
  end

  def call
    # My code here
  end
end

but this fails with the following message:

message: "undefined method `key?' for #<Conversation:0x0000556d16a5d948>"
...

A dirty workaround is to create a second context attribute storing the model's attributes and use that one instead:

Another interactor running before the next one:

class CreateConversation
  include Interactor
  include Interactor::Contracts

  promises do
    required(:conversation).filled
    required(:conversation_hash).filled # <=== We promise to provide this
  end

  def call
    context.conversation = create_conversation
    context.conversation_hash = create_conversation.attributes # <=== Get a Hash of the model
  end
end
class EnqueueMessagingJob
  include Interactor
  include Interactor::Contracts

  expects do
    required(:conversation_hash).schema do  # <=== Now it respond to `key?`
      required(:type).filled(included_in?: %w[email sms])
      # ...
    end
  end

  def call
    # My code here
  end
end

And this works.

It would be great to call attributes on the given context item when it is a class which respond_to?(:attributes).

What do you think about that?

zedtux avatar Oct 20 '20 07:10 zedtux