Skip to content

Instantly share code, notes, and snippets.

@vecerek
Last active January 30, 2018 13:11
Show Gist options
  • Save vecerek/0a7ccbb99ab6fbc7bdf5b4963ae5f414 to your computer and use it in GitHub Desktop.
Save vecerek/0a7ccbb99ab6fbc7bdf5b4963ae5f414 to your computer and use it in GitHub Desktop.
  • Memoization
    • Parametric memoization (using the special Hash constructor):
    Hash.new {|h, key| h[key] = some_calculated_value }
    class City < ActiveRecord::Base
      def self.top_cities(order_by)
        @top_cities ||= Hash.new do |h, key|
          h[key] = where(top_city: true).order(key).to_a
        end
        @top_cities[order_by]
      end
    end
    • Memoizing false or nil values:
    def has_keys?
      return @has_keys if defined? @has_keys
    
      @has_keys = some_logic_here
    end
  • Concerns, service objects, and tableless models
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment