0

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.

2
  • Can you tell us why you're stressing on "function, not a method..."? How are they different? Commented Apr 19, 2014 at 14:49
  • Why do you want such thing? Even in modern PHP applications for these are used methods, but from static classes, i.e. App::debug($var) available in all your scope via autoloader Commented Apr 19, 2014 at 14:53

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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).

Comments

0

There are no functions in Ruby, what you want is not possible.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.