I am new to Rails. I came from a Codeigniter background. I am having a hard time finding resources on Rails 3.0 for beginners. I read my new Rails book but am still confused about a few things.
How do I include my libraries or helpers into a controller? Do I use an "include" or "require"?
The 2nd question is how do I dynamically load plugins? Let say I have 1,000 plugins. I don't want them to be all initialized. Is there a way to co开发者_如何学Pythonntroller which plugin are initialized from controllers?
When your app starts it will run all the scripts in yourapp/config/initializers
, there you can add some stuff that you want always present.
in yourapp/config/application.rb
you can add
config.autoload_paths += %W(#{config.root}/lib)
inside the class Application
declaration.
Then any time you use a class it doesn't know about like SomeNewClass.new "param"
rails will try to autoload yourapp/lib/some_new_class.rb
As for your second question I don't know. I have never used more than a few plugins.
Unlike PHP (Codeigniter), in Ruby require
and include
are very different in behaviour.
require
loads a given path (somewhat like PHP) while include
is usually used to include a Module
in a Class
.
require
is a method from Kernel
while include
acts more like an object of class Class
. Try -
Kernel.respond_to? :require
include.is_a? Class
Before jumping on Rails, I suggest you to read on Ruby. I suggest this book and http://en.wikibooks.org/wiki/Ruby_programming_language.
For Ruby on Rails, I recommend -
- http://guides.rubyonrails.org/
- http://api.rubyonrails.org/
For 2nd question, I guess, initialising plugins is part of Rails' initialisation process, so it probably can not be selective (but I'm not sure). See http://ryanbigg.com/guides/initialization.html for more information.
The most easiest way to avoid a plugin from being initialised is to put it in some path which is not in Rails' (auto)load_paths
, say vendor/extensions
and require
them in controllers when needed using
require "vendor/extensions/example-plugin/lib/example-plugin"
However, I recommend against it and suggest to wait until your plugin count reaches 1000/10. :)
精彩评论