ruby memoization

156

# Basic memoization
class User < ActiveRecord::Base
  def twitter_followers
    # assuming twitter_user.followers makes a network call
    @twitter_followers ||= twitter_user.followers
  end
end

# Multiline memoization
class User < ActiveRecord::Base
  def main_address
    @main_address ||= begin
      maybe_main_address = home_address if prefers_home_address?
      maybe_main_address = work_address unless maybe_main_address
      maybe_main_address = addresses.first unless maybe_main_address
    end
  end
end

# Memoization with null being a valid value
class User < ActiveRecord::Base
  def twitter_followers
    return @twitter_followers if defined? @twitter_followers
    @twitter_followers = twitter_user.followers
  end
end

# Memoization for hashes
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

Comments

Submit
0 Comments

More Questions

rails migration update column default valuerails remove model ruby get current datetime
Your Ruby version is 3.0.0, but your Gemfile specified 2.7.4rails kill server iterate over string ruby
ruby hash mergehow to I change the name of a column in rails how to remove columns from rails
contains ruby arrayruby is int ruby each do method
ruby iterate over arrayruby array has element drop rails all db
destroy existed porthow to check ruby version kill puma pid local
kill port already in useif contains ruby rails remove column from model
rails image tagAdd references rails migration how to delete a table in rails
if the version you need is missing, try upgrading ruby-build.error: while executing gem ... (gem::filepermissionerror) how to convert a string to lower or upper case in ruby
find records created in a particular month railsdb migration rollback specific migration rails how to get associations from a model in rails
how to select first n data in an array rubyruby glob all nested file except directories destroy parent when you destroy child rails
how to turn string array to int array rubyruby iterate over each character in string rails api only with postgress and rspec
rails api active storage get image urlcreate rails app in current directory rails validate no special characters
ruby refinement import dynamic methodsread file in ruby with relative path how to see rails routes in browser
rails model validate integer rangeruby struct with keyword arguments ruby remove unsafe file characters
ruby extract filename from pathgenerate controller for devise rails engine table doesnt exist