[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

where to put require

Ike

10/20/2006 2:22:00 PM

If I have a rails app and I need to put in
require 'xxx'
include yyy

in my class ApplicationController < ActionController::Base

Where within this application.rb file do I put these lines? Thanks, Ike



3 Answers

Bira

10/20/2006 2:33:00 PM

0

On 10/20/06, Ike <rxv@hotmail.com> wrote:
> If I have a rails app and I need to put in
> require 'xxx'
> include yyy
>
> in my class ApplicationController < ActionController::Base
>
> Where within this application.rb file do I put these lines? Thanks, Ike

It's usually best to put it in the first lines of the file, before any
variable declarations or class definitions. They're a bit like C's
"<includes>" or Java's "imports".


--
Bira
http://compexplicita.bl...
http://sinfoniaferida.bl...

Jano Svitok

10/20/2006 2:44:00 PM

0

On 10/20/06, Bira <u.alberton@gmail.com> wrote:
> On 10/20/06, Ike <rxv@hotmail.com> wrote:
> > If I have a rails app and I need to put in
> > require 'xxx'
> > include yyy
> >
> > in my class ApplicationController < ActionController::Base
> >
> > Where within this application.rb file do I put these lines? Thanks, Ike
>
> It's usually best to put it in the first lines of the file, before any
> variable declarations or class definitions. They're a bit like C's
> "<includes>" or Java's "imports".

And be careful where you place include Yyy as the placement influences
where the module will be mixed in.

It's different when you do

include Forwardable
class X
...
end

and

class X
include Forwardable
...
end

Sometimes (=rarely), when you want to require later or not at all,
it's useful to put require inside a method.

Rubén Medellín

10/20/2006 6:36:00 PM

0


Jan Svitok wrote:

> Sometimes (=rarely), when you want to require later or not at all,
> it's useful to put require inside a method.

Just to make it a little clearer, by experimenting you can see:

-------------
def check
a = ['foo', 'bar', 'baz'] * 2
begin
a.each_slice(3) {|slice| p slice}
rescue Exception
puts "No such method\n"
end
require 'enumerator'
a.each_slice(3){|slice| p slice}
end

#Test starts here

begin
x.each_slice(3) {|slice| p slice}
rescue Exception
puts "No such method\n"
end

puts $".include?('enumerator.so')

check

puts $".include?('enumerator.so')

x = ['foo', 'bar', 'baz'] * 2
x.each_slice(2) {|slice| p slice}
---------------
Produces ->
No such method
false
No such method
["foo", "bar", "baz"]
["foo", "bar", "baz"]
true
["FOO", "BAR"]
["BAZ", "FOO"]
["BAR", "BAZ"]

As you can see, 'require' is itself a method (btw, mixed with the
require method of rubygems/custom_require.rb if specified), that calls
a library and adds it to $". Such library is called the first time is
required. So, as Jan said, you may call it anywhere on your program
depending on where do YOU require it.