简体   繁体   中英

How can i declare function (not method) with ruby on rails?

I give you an function exemple:

def debug(var)
    raise var.inspect
end

in PHP its simple, I put

function debug($var)
{
    var_dump($var);
}

and I just have to include the file where is define this function and it is aviable in all my code where and when I want.

How can I do the same in rails app? I want a function, not a method in class and i want to be able to call it evrywhere in my code.

You can define the method in a module, and then include the module wherever you need access to the method, as follows:

module SomeModule
  def debug(var)
    raise var.inspect
  end
end

And then in another class:

class SomeClass
  include SomeModule

  def some_method
    debug(self)
  end
end

It's bad design to add global functions, btw they wont be functions: if you attach something to the global namespace, it will still be a method: remember in Ruby everything is an object.

Attach it to a module.

Example:

module Utils

  def self.debug(var)  
    raise var.inspect
  end
end

And use it wherever needed:

Utils.debug(something)

Let's start by saying that what you show as a function in first example is a method.

In Ruby everything is an object. So if you define some method just like in your first example, it still belongs to some object.

irb(main):001:0> self
=> main
irb(main):002:0> self.class
=> Object

You see, even if you just call irb , the context you execute code is an instance of Object class.

So what you actually want is a method which is available globally in scope of Rails application. You can achieve it by including some module right in your application (like in other answers to this question)

However, I suggest different way. Instead of creating a global method, create a class/module with that method. Classes and modules are globally accessible, so you will be able to use it everywhere (see fivedigit's answer for example).

Ruby中没有函数,你想要的是不可能的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM