Project

General

Profile

Actions

Feature #20202

closed

Memoized endless method definitions

Added by matheusrich (Matheus Richard) 10 months ago. Updated 9 months ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:116369]

Description

I propose introducing a shorthand for memoized endless method definitions:

class Foo
  def bar ||= :memoized_value

  # It should behave like
  def bar = (@bar ||= :memoized_value)
end

Not only is this shorter and (IMO) a natural follow-up for endless method definitions, but it's also a common pattern on Ruby codebases. It's very useful to decompose responsibilities into several objects:

class User
  def notifications_enabled? = settings.notifications?
  def enable_notifications = (settings.notifications = true)
  def disable_notifications = (settings.notifications = false)

  private

  def settings = @settings ||= Settings.new(self)
end

class User::Settings
  attr_writer :notifications

  def initialize(user)
    @user = user
    @notifications = false
  end

  def notifications? = @notifications
end

u = User.new
u.notifications_enabled? # => false
u.enable_notifications
u.notifications_enabled? # => true

In the example, the settings method could be rewritten as

  def settings ||= Settings.new(self)
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0