views:

60

answers:

2

Hello all,

I have this code snippets that generates a signature for POSTs. The detail of it is not important, but what I want to know is: since it is not a model-related chunk of code, it really can be use anywhere: in controllers, in models, in view helpers; even in views. So I am unsure where and, even bigger of a problem, how to activate the use of it once I place it in some location.

Is it what those "require" statements are all about? That you can acquire some functionality through a "require" statement in the current file you are working on?

Just so that we have an example to talk about, say, I have a little snippet of code that does cubing:

def cube_it(num)
  num**3
end

I know that I will be using it in various places across the application, so where should I put it? and when I do need to use it, how can I "summon" it?

Thank You

A: 

Rails autoloads modules and classes when they are first used. You can put your function into a module (or class) and put the file into the lib directory in your application. require statements aren't used in Rails apps often.

Alex - Aotea Studios
Thanks for your response Alex ---say I made a file call maths.rb, so I put it in the "lib" directory? and after that I can call cube_it from anywhere?
Nik
@Nik: yes, just put it in the lib directory. If you put cube_it in a module, the module will be autoloaded. I haven't tried it with plain functions though.
Alex - Aotea Studios
Okay, I made a file lib/maths.rb. and in it, it is simply :class Maths def cube_it(n) n**3 endendBut when I load up the script/console and tried cube_it(3), it says no method error.I tried module Maths def cube_it(n) n**3 endendand no luck. ----just a second, in the console, I did a "include Maths", then it worked! But you mentioned it being autoloaded?
Nik
When he says autoload, it's not quite the right word to use. When the rails framework comes across an unknown constant (Math in this case), it will try to require 'math'. Since a lot of the rails folders are in the load path for ruby, it finds it easily.
Samuel
@Nik: you need to make it a class method, like Samuel suggests in his answer, and call it with `Math.cube_it(3)`. Then it should work.
Alex - Aotea Studios
A: 

I would suggest putting your code inside a module named Math in lib/math.rb.

math.rb
module Math
  class << self
    def cube_it(num)
      num*3
    end
  end
end

You don't need any require statements with this (rails does it for you) and you can easily call it with Math.cube_it("Hi").

There are other ways of adding code to a rails application, but this is the best way.

Samuel
I see. thanks Samuel
Nik