Hi all,
I want to define some simple classes that can be created and passed
around in views. I’m currently using hashes, but I want to use a class
so I can assign default values. Is this possible? Where would I define
these classes? Thanks!
Abhik
apramanik wrote:
I want to define some simple classes that can be created and passed
around in views. I’m currently using hashes, but I want to use a class
so I can assign default values. Is this possible? Where would I define
these classes? Thanks!
Your application’s “lib” directory will be in the Ruby load path and by
default, when Rails comes across something starting with a capital
letter it will “require” a file of the lower cased name (with words
separated by underscores). This all means that, if you place a class
MyClass in the file lib/my_class.rb then it will automatically be loaded
when it is needed. This is the usual place to put classes which are not
ActiveRecord models. You can then access this class from any model,
view or controller code.
Ah ok. That worked. I had put my file in a folder under ‘lib’. Is
there a way to keep it in a subdirectory of ‘lib’ and require it
elsewhere?
Abhik
On Mar 22, 5:45 am, Mark B. [email protected]
apramanik wrote:
Ah ok. That worked. I had put my file in a folder under ‘lib’. Is
there a way to keep it in a subdirectory of ‘lib’ and require it
elsewhere?
Yes. Rails relates subdirectories to namespaces. For example, you
could have the class Admin::Something in the file lib/admin/something.rb
and Rails will find it automatically.
If you want to put classes into subdirectories without namespaces then
you need to tell Rails where to find the class definitions using
“require”.
apramanik wrote:
Great that worked also. I also tried out doing a require in the erb,
didn’t work.
No, you’ll have to load it in elsewhere, such as your
config/environment.rb file.
Great that worked also. I also tried out doing a require in the erb,
didn’t work.
On Mar 22, 9:02 am, Mark B. [email protected]
Ok great thanks for all your help!
On Mar 22, 9:27 am, Mark B. [email protected]