Project

General

Profile

Actions

Feature #11361

open

proposal for easy method to nil-guard for generated variable name.

Added by masarakki (masaki yamada) over 9 years ago. Updated almost 9 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:70009]

Description

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)
  variable_name = "@user_#{id}"
  instance_variable_set(variable_name, User.find(id)) unless instance_variable_defined?(variable_name)
  instance_variable_get(variable_name)
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(variable_name, &block)
  instance_variable_set(variable_name, block.call) unless instance_variable_defined?(variable_name)
  instance_variable_get(variable_name)
end

Updated by marcandre (Marc-Andre Lafortune) over 9 years ago

Isn't this simpler (and easier to read):

@cache ||= {}
@cache[id] ||= User.find(1)

I can't recall ever needing to do what you want to do.

Updated by jwmittag (Jörg W Mittag) almost 9 years ago

masaki yamada wrote:

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)
  variable_name = "@user_#{id}"
  instance_variable_set(variable_name, User.find(id)) unless instance_variable_defined?(variable_name)
  instance_variable_get(variable_name)
end

Note that the two examples you gave are not equivalent: the first assigns to the variable if it evaluates to false or nil regardless of whether it is defined or not, the second only assigns if it is undefined. Which one of the two do you want?

Actions

Also available in: Atom PDF

Like0
Like0Like0