Skip to content

Instantly share code, notes, and snippets.

@phuibonhoa
Created August 21, 2014 10:06
Show Gist options
  • Save phuibonhoa/974aae201421f0177c92 to your computer and use it in GitHub Desktop.
Save phuibonhoa/974aae201421f0177c92 to your computer and use it in GitHub Desktop.
use memoized attributes instead of process methods
# Memoized facade attribute
# √ Lazy loaded
# √ Better encapsulated / more 'atomic'. Processing introduces unnecessary depencies at different times of the life cycle of the object.
# √ More idiomatic mindset to think of these are 'attributes' on an object, than results of a calculation
# Memoized attribute
class RecommendationCalculator
attr_reader :user
def initialize(user:)
@user = user
end
def recommendations
@recommendations ||= (
# calculate recommendations
)
end
end
# Process / Calculate method
class RecommendationCalculator
attr_reader :user, :calculated_recommendations
def initialize(user:)
@user = user
@calculated_recommendations = calculate_recommendations(user: user, location: user.current_location)
end
private
def calculate_recommendations(user:, location:)
# calcualte recommendations based on user and location
end
end
@michaelgpearce
Copy link

There is a "gotcha" when using ||= memoization - specifically memoizing an object that evaluates to false. This doesn't come up often, but can be a difficult to track down.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment