How to implement attr that takes time to generate in ruby

Asked 2 years ago, Updated 2 years ago, 86 views

There are currently classes like this.

class Hoge
  attr_accessor:fuga, :piyo

  def initialize
    data_create
  end

  def data_create
    data = various actions {...}

    # substitute for instance variable
    @fuga=data[:a]
    @piyo=data[:b]
  end
end

# when using
hoge = Hoge.new
hoge.hufa
hoge.piyo

Hoge#datacreate actually takes some time to retrieve information via http and perform the conversion process.
Therefore, each time an instance is generated, the overhead costs are incurred.

I don't always use @fuga or @piyo when I use the Hoge class, so I thought it would be better to create data at the first time you see it.

Specifically, the code is as follows:

class Hoge
  @fuga=nil
  @piyo=nil

  def fuga
    data_create [email protected]?

    @fuga
  end

  def piyo
    data_create [email protected]?

    @piyo
  end


  def data_create
    data = various actions {...}

    # substitute for instance variable
    @fuga=data[:a]
    @piyo=data[:b]
  end
end


# when using
hoge = Hoge.new
hoge.hufa
hoge.piyo

I'm not very experienced in programming, so I'm not confident that this is a good way to do-it-yourself approach.
If there is anything I should be careful about, could you tell me?

Please let us know your idea of "I would do this if I were you".

Also, please let me know if there is a way to write like ruby.
Thank you for your cooperation.

ruby-on-rails ruby

2022-09-30 21:17

1 Answers

data may be misguided because I don't know what information it is, but
If I were you, I would write like this.

class Hoge
  def fuga
    data [:a]
  end

  def piyo
    data [:b]
  end

  def data
    @data||= Various actions {...}
  end
end

If the instance variable @data is nil when the method data is referenced, various actions are performed, and @data is returned immediately if it already contains a value.


2022-09-30 21:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.