Canna
Canna

Reputation: 3794

What require magic is happening in rails here?

I started Rails without NO fundamental Ruby knowledge.

and now i'm here in require, load, include, extend questions

I have learned that if it is a separated file

in Ruby, you MUST contain require or load 'file path'

If it is like this, in my application_controller there needs to be a bunch of requires,

if i want to include bunch of helpers.

ex>

require 'path_to_the_helpera.rb'
require 'path_to_the_helperb.rb'
class ApplicationController < ActionController:Base
  include HelperA
  include HelperB
end

But as you all know, no require is in Rails app(except external library in lib folder)

I'm assuming that inside config folder will do this magic....it is pretty hard for a noob like me

Upvotes: 0

Views: 70

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84114

Rails adds a const_missing hook so that when you reference an unloaded constant it will first try and load it for you instead of raising a NameError.

There is a rails guide with an extensive discussion of how it does this, pitfalls and tips but the main thing is that you need to name things inline with the conventions, ie a class or module called FooBar should be in foo_bar.rb in one of the folders in rails' search path.

Upvotes: 2

Simone Carletti
Simone Carletti

Reputation: 176352

I started Rails without NO fundamental Ruby knowledge.

This is definitely not the best approach.

Rails heavily uses conventions. Therefore, if you place an helper in the /app/helpers folder, and you name it according to the conventions, it will be automatically loaded and included in your app.

For instance

# file /app/helpers/foo_helper.rb
module FooHelper
  def print_foo
    puts "foo!"
  end
end

Now you can simply call print_foo in a view, and it will work.

Upvotes: 2

Related Questions