Topic: How To Create Components

Hey,

I have to say, that I am very new to RoR.

My question is, how and where to write scripts that can be used from all Controllers.


For example, I just wrote a little action in a controller, that converts latitude and longtitude into tilepaths of openstreetmaps. My intention is to write my code the DRY way. So, how can I use this little script from all my other controllers? And where can I save it, if I don't want to have it in the Controllers folder?


Cheers

Re: How To Create Components

There are a couple of ways of doing this depending on how you feel
The simplest option is to crate a class and put the file in your projects libs folder then just use it as you would any other class

If you want to share this functionality with others including other apps you may want to use it in then make a gem which sounds far more complicated than it is
check out this railscast on how to make a gem http://railscasts.com/episodes/245-new-gem-with-bundler it really is simple to do

using a module is another way and combining modules with classes is yet another way of namespacing the class so you don't get conflicts with names

Modules work much the same as a class. It's just a place holder to store methods that can then be included wherever you want it's kind of the equivalent of a java library and can not be created as a class. You can use a module to mix in class methods and instance methods into any other class just by including the file in whatever classes want that functionality. It's kinda like a neat work around for not having multiple inheritance

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)

Re: How To Create Components

Any reason you wouldn't want to use ApplicationController?  You can then call functions contained there from any of your application's controllers.  Or, you could put it into a helper file and then include the helper file in the application controller...and that would also make the helper (and all of its contents) available to all controllers in your application. 

Not sure if either of the above are the most railsey ways but it should get you to where you need to be and is certainly a better option than writing the same code in each of your controllers.