Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make callable attribute in Ruby

Tags:

ruby

I do not know how to google it, but i know what i want.

i want to make something like this

class SchedulingManager
  attr_accessor :on_start

  def call
    on_start
  end
end

scheduling = SchedulingManager.new
scheduling.on_start do
  puts "hello"
end

so i want my on_start here to be initiate by do block style. and save it so i can call in method call and print hello (or do whatever code in the block).

i do not know what the name of it, i also do not know how to google it.

Kindly need your help guys, thanks

like image 542
Dedy Puji Avatar asked Jun 26 '26 12:06

Dedy Puji


1 Answers

I would do it like this and store the block in a variable.

class SchedulingManager
  def on_start(&block)
    @block = block
  end

  def call
    @block&.call
  end
end

scheduling = SchedulingManager.new
scheduling.on_start do
  puts "hello"
end

scheduling.call
#=> hello
like image 190
spickermann Avatar answered Jul 06 '26 06:07

spickermann