Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make sure .valid? called only once #125

Closed
mrwokkel opened this issue Jan 31, 2014 · 6 comments
Closed

Make sure .valid? called only once #125

mrwokkel opened this issue Jan 31, 2014 · 6 comments
Assignees
Labels

Comments

@mrwokkel
Copy link

I ran into an issue where the execute code changes the conditions for an interaction to be valid.

For instance uniqueness of something. When .valid? is called again, after execute, these conditions are not valid anymore.

@tfausak
Copy link
Collaborator

tfausak commented Jan 31, 2014

Good catch! If I understand you correctly, this example shows what you're talking about:

class ClearArray < ActiveInteraction::Base
  array :array

  validate { errors.add(:array, 'is empty') if array.empty? }

  def execute
    array.clear
  end
end
ClearArray.run!(array: [1, 2, 3])
# => ActiveInteraction::InvalidInteractionError: Array is empty
outcome = ClearArray.run(array: [1, 2, 3])
outcome.valid?
# => nil
interaction = ClearArray.new(array: [1, 2, 3])
interaction.valid?
# => true
interaction.execute
# => []
interaction.valid?
# => nil

@mrwokkel
Copy link
Author

Yes. And your examples in the README should better use errors.empty? or something of the like.

@tfausak
Copy link
Collaborator

tfausak commented Jan 31, 2014

I think this is a bug. You should be calling outcome.valid? instead of outcome.errors.empty?.

@mrwokkel
Copy link
Author

You are right. What I meant was a way of asking interaction_object.errors.empty?. Also when the outcome has an uniqueness validation it will fail after the run method.

The way I do it now is:

# Something model has an uniqueness validation
@create_something = CreateSomething.new(params[:create_something])
if @create_something.save # just calls private method .run internally like so: run.present?
  # outcome.valid? will return false if called after .run because something is not unique anymore
  redirect_to something_url(@create_something.outcome)
else
  render :new
end

I hope I make sense :).

@mrwokkel
Copy link
Author

Ah language. I think you already caught my drift.

@tfausak tfausak self-assigned this Feb 4, 2014
@tfausak tfausak closed this as completed in 0b4f267 Feb 4, 2014
@tfausak
Copy link
Collaborator

tfausak commented Feb 4, 2014

Fixed in version 1.0.1. Thanks for reporting this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants