Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a module function in a ruby module

Tags:

module

ruby

I want to call a module function to define a constant in a utility module in ruby. However, when I try this I get an error message. Here comes the code and the error:

module M
  ABC = fun

  module_function

  def self.fun
    "works"
  end
end

Error message:

NameError: undefined local variable or method `fun' for M:Module

Any ideas? I also tried it without self and with M.fun but no success...

like image 972
grackkle Avatar asked Jun 10 '26 20:06

grackkle


1 Answers

It is just that the method is not defined when you assign fun to ABC. Just change the order:

module M
  def self.fun
    "works"
  end

  ABC = fun
end

M::ABC
#=> "works"

If you dislike the order (constants below methods), you might want to consider to have the method itself to memorize its return value. A common pattern looks like:

module M
  def self.fun
    @cached_fun ||= begin
      sleep 4     # complex calculation
      Time.now    # return value
    end
  end
end

M.fun
# returns after 4 seconds => 2017-03-03 23:48:57 +0100
M.fun
# returns immediately => 2017-03-03 23:48:57 +0100
like image 124
spickermann Avatar answered Jun 13 '26 12:06

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!