Skip to content

Instantly share code, notes, and snippets.

@masarakki
Created July 17, 2015 08:22
Show Gist options
  • Save masarakki/d44a38b810ff267c489f to your computer and use it in GitHub Desktop.
Save masarakki/d44a38b810ff267c489f to your computer and use it in GitHub Desktop.
proposal for instance_variable_get_or_set

It's easy to 'nil guard' for normal variable.

def user
  @user ||= User.find(1)
end

but it's not simple for generated variable name.

def user(id)
  valname = "@user_#{id}"
  instance_variable_set(valname, User.find(id)) unless instance_variable_defined?(valname)
  instance_variable_get(valname)
end

I want to write it like this.

def user(id)
  instance_variable_get_or_set("@user_#{id}") { User.find(1) }
end

it can be implemented by this code.

def instance_variable_get_or_set(valname, &block)
  instance_variable_set(valname, block.call) unless instance_variable_defined?(valname)
  instance_variable_get(valname)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment