Define classes for use in views

5,956 views
Skip to first unread message

apramanik

unread,
Mar 22, 2008, 4:12:35 AM3/22/08
to Ruby on Rails: Talk
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

Mark Bush

unread,
Mar 22, 2008, 8:45:01 AM3/22/08
to rubyonra...@googlegroups.com

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.

--
Posted via http://www.ruby-forum.com/.

apramanik

unread,
Mar 22, 2008, 11:50:08 AM3/22/08
to Ruby on Rails: Talk
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 Bush <rails-mailing-l...@andreas-s.net>
wrote:

Mark Bush

unread,
Mar 22, 2008, 12:02:20 PM3/22/08
to rubyonra...@googlegroups.com
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

unread,
Mar 22, 2008, 12:17:20 PM3/22/08
to Ruby on Rails: Talk
Great that worked also. I also tried out doing a require in the erb,
didn't work.

On Mar 22, 9:02 am, Mark Bush <rails-mailing-l...@andreas-s.net>
wrote:

Mark Bush

unread,
Mar 22, 2008, 12:27:31 PM3/22/08
to rubyonra...@googlegroups.com
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.

apramanik

unread,
Mar 22, 2008, 12:29:35 PM3/22/08
to Ruby on Rails: Talk
Ok great thanks for all your help!

On Mar 22, 9:27 am, Mark Bush <rails-mailing-l...@andreas-s.net>
wrote:
Reply all
Reply to author
Forward
0 new messages