Skip to content

Instantly share code, notes, and snippets.

@mikekreeki
Last active August 29, 2015 14:05
Show Gist options
  • Save mikekreeki/081a3a42393e324fa31d to your computer and use it in GitHub Desktop.
Save mikekreeki/081a3a42393e324fa31d to your computer and use it in GitHub Desktop.
One big reason to pick ActiveInteraction to implement Command pattern in Rails apps over rolling you own solution using Virtus and ActiveModel::Model
class Foo < ActiveInteraction::Base
string :bar
# additional validations
# validates :bar, ...
def execute
unless do_something
errors.add :bar, 'is not cool'
end
end
def do_something
false
end
end
command = Foo.run(bar: nil)
command.valid? #=> false
command.errors.full_messages
#=> ["Bar is required"]
command = Foo.run(bar: 'test')
command.valid? #=> false
command.errors.full_messages
#=> ["Bar is not cool"]
# Therefore..
command = Foo.run(bar: 'test')
if command.valid?
redirect_to root_path
else
render :new
end
class Foo
include Virtus.model
include ActiveModel::Model
attribute :bar, String
# This validation needs to be here since Virtus does
# not require attributes to be present be default
validates :bar, presence: true
def execute
unless do_something
errors.add :bar, 'is not cool'
end
end
def do_something
false
end
end
command = Foo.new(bar: nil)
command.valid? #=> false
command.errors.full_messages
#=> ["Bar can't be blank"]
command = Foo.new(bar: 'test')
command.valid? #=> true (!!!)
command.execute
command.valid? #=> false
command.errors.full_messages
#=> ["Bar is not cool"]
# Therefore..
command = Foo.new(bar: 'test')
# Runs ActiveModel validations..
if command.valid?
command.execute
# Still valid after execute? (!!!)
if command.valid?
redirect_to root_path
else
render :new
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment