Last active
May 4, 2018 00:18
-
-
Save stephaneliu/97184f87376cacec5920c2c974bba4c3 to your computer and use it in GitHub Desktop.
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
class Event < ApplicationRecord | |
# Before | |
def cateorized? | |
event.category.present? ? event.category.name != 'none' : false | |
end | |
# Refactor - simplify with Null test with AND operator | |
def categorized? | |
event.category && event.category != 'none' | |
end | |
# Refactored with Null Object pattern with duck typing but it still violates Law of Demeter | |
def categorized? | |
(event.category.presence || OpenStruct.new(name: 'none')).name != 'none' | |
end | |
end | |
# Refactor #2 - add delegate to class | |
class Event | |
delegate :categorized?, to: :category | |
end | |
class Category < ApplicationRecord | |
def categorized? | |
name && name != 'none' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment