Skip to content

Instantly share code, notes, and snippets.

@stephaneliu
Last active May 4, 2018 00:18
Show Gist options
  • Save stephaneliu/97184f87376cacec5920c2c974bba4c3 to your computer and use it in GitHub Desktop.
Save stephaneliu/97184f87376cacec5920c2c974bba4c3 to your computer and use it in GitHub Desktop.
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