Last active
May 25, 2022 02:50
-
-
Save joemasilotti/e7919817595b950e5fa078d26e9b6aa0 to your computer and use it in GitHub Desktop.
ResultType
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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