Skip to content

Instantly share code, notes, and snippets.

@simonista
Last active February 10, 2016 19:54
Show Gist options
  • Save simonista/ae3dec376a3272c0782b to your computer and use it in GitHub Desktop.
Save simonista/ae3dec376a3272c0782b to your computer and use it in GitHub Desktop.
Send me your cleanest version of this function
# Current gotcha's:
# - any result to be cached in the ivar (currently not true for the early return)
# - if any of the early return stuff, or if the session.key is created, we don't want to run brand_config_for_account(opts)
def active_brand_config(opts={})
@active_brand_config_cache ||= {}
return @active_brand_config_cache[opts] if @active_brand_config_cache.key?(opts)
@active_brand_config_cache[opts] = begin
return nil if !use_new_styles? || (@current_user.try(:prefers_high_contrast?) && !opts[:ignore_high_contrast_preference])
brand_config = if session.key?(:brand_config_md5)
BrandConfig.where(md5: session[:brand_config_md5]).first
else
brand_config_for_account(opts)
end
if !brand_config && k12?
brand_config = BrandConfig.k12_config
end
brand_config
end
end
@ccutrer
Copy link

ccutrer commented Feb 10, 2016

def active_brand_config_cache
  @active_brand_config_cache ||= {}
end

def active_brand_config(opts={})
  active_brand_config_cache.fetch(opts) do
    if !use_new_styles? || (@current_user.try(:prefers_high_contrast?) && !opts[:ignore_high_contrast_preference])
      next active_brand_config_cache[opts] = nil
    end
    brand_config = if session.key?(:brand_config_md5)
      BrandConfig.where(md5: session[:brand_config_md5]).first
    else
      brand_config_for_account(opts)
    end
    brand_config ||= BrandConfig.k12_config if k12?
    active_brand_config_cache[opts] = brand_config
  end
end

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