Skip to content

Instantly share code, notes, and snippets.

@joemasilotti
Last active May 25, 2022 02:50
Show Gist options
  • Save joemasilotti/e7919817595b950e5fa078d26e9b6aa0 to your computer and use it in GitHub Desktop.
Save joemasilotti/e7919817595b950e5fa078d26e9b6aa0 to your computer and use it in GitHub Desktop.
ResultType
module ResultType
extend ActiveSupport::Concern
module ClassMethods
def define_type(type)
define_method "#{type}?" do
true
end
end
end
def method_missing(m, *args, &block)
m.ends_with?("?") ? false : super
end
def respond_to_missing?(*args)
true
end
end
class BusinessesController
def create
result = Businesses::Profile.new.create(business_params)
if result.success?
redirect_to business_path(result.business)
elsif result.special_case?
redirect_to special_path
else
@business = result.business
render :new, status: :unprocessable_entity
end
end
end
class Businesses::Profile
def create(options)
business = Business.new(options)
if business.name == "Secret Business"
SpecialCase.new
elsif business.save
Success.new(business)
else
Failure.new(business)
end
end
private
Success = Struct.new(:business) do
include ResultType
define_type :success
end
Failure = Struct.new(:business) do
include ResultType
define_type :failure
end
class SpecialCase
include ResultType
define_type :special_case
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment