Skip to content

Instantly share code, notes, and snippets.

@adz
Created October 6, 2014 14:26
Show Gist options
  • Save adz/b149cb900e459f07850c to your computer and use it in GitHub Desktop.
Save adz/b149cb900e459f07850c to your computer and use it in GitHub Desktop.
Simple null object
class CoursesController < ApplicationController
expose(:course, attributes: :course_params)
expose(:current_course) { current_user.courses.find_by_id(params[:id] || params[:course_id]) }
expose(:first_of_each_month_of_course) { (current_course.start_date.change(day: 1)..current_course.end_date).select{ |d| d.day == 1 } }
# ...
end
# Orginal code gives:
# line 4 of [PROJECT_ROOT]/app/controllers/courses_controller.rb: block in <class:CoursesController>
NoMethodError - undefined method `start_date' for nil:NilClass
class CoursesController < ApplicationController
expose(:course, attributes: :course_params)
expose(:current_course) { id = params.fetch(:id) { params.fetch(:course_id) }
current_user.courses.find_by_id(id) }
expose(:first_of_each_month_of_course) { (current_course.start_date.change(day: 1)..current_course.end_date).select{ |d| d.day == 1 } }
end
# Now code gives:
# line 3 of [PROJECT_ROOT]/app/controllers/courses_controller.rb: block in <class:CoursesController>
KeyError: key not found: :course_id
...looup gary's sentinel object
class Client < ActiveRecord::Base
belongs_to :pricing_level
end
class PricingLevel
def self.find_default
#...
end
end
class Guest
def name
'Guest'
end
def pricing_level
PricingLevel.find_default
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment