Skip to content

Instantly share code, notes, and snippets.

View kklimuk's full-sized avatar

Kirill Klimuk kklimuk

View GitHub Profile
def users_with_discounts
User.includes(payment_plan: :discounts).where(paying: true).to_a
end
def users_with_discounts
@users_with_discounts ||= User.includes(payment_plan: :discounts).where(paying: true).to_a
end
def users_with_discounts
return @users_with_discounts unless @users_with_discounts.nil?
users = User.includes(payment_plan: :discounts).where(paying: true).to_a
@users_with_discounts = users.select do |users|
users.payment_plan.discounts.any? && !users.payment_plan.delayed?
end
end
def users_with_discounts(scoped_to={})
@users_with_discounts ||= {}
return @users_with_discounts[scoped_to] if @users_with_discounts.has_key?(scoped_to)
users = User.includes(payment_plan: :discounts).where(
paying: true,
**scoped_to
).to_a
@users_with_discounts[scoped_to] = users.select do |users|
def users_with_discounts
@users_with_discounts ||= computation_that_returns_nil
end
def users_with_discounts
return @users_with_discounts unless @users_with_discounts.nil?
@users_with_discounts = computation_that_returns_nil || false
end
memoized
def users_with_discounts(scoped_to={})
users = User.includes(payment_plan: :discounts).where(paying: true, **scoped_to).to_a
users.select do |users|
users.payment_plan.discounts.any? && !users.payment_plan.delayed?
end
end
module RubyMemoized
class Memoizer
attr_reader :context, :method
def initialize(context, method)
@context = context
@method = method
end
def call(*args, &block)
class FibonacciCalculator
include RubyMemoized
def calculate(n)
return n if (0..1).include?(n)
calculate(n - 1) + calculate(n - 2)
end
memoized
require 'benchmark'
Benchmark.bm do |measurer|
calculator = FibonacciCalculator.new
measurer.report 'with memoization' do
10.times { calculator.memoized_calculate(35) }
end
measurer.report 'without memoization' do