Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails lib directory

Question about lib directory.

What are good practices in using the lib directory?
When should it be used over app/models or app/helpers?
And somewhat related how do you get Rails 3 to include files from the lib directory?

Thanks

like image 455
GTDev Avatar asked Oct 12 '11 07:10

GTDev


People also ask

What is the lib directory for in Rails?

In Rails's directory structure as far back as I can recall, there's always been a lib folder. This folder is for files that don't belong in the app folder (not controllers, helpers, mailers, models, observers or views), such as modules that are included into other areas of the application.

What is the lib directory?

The lib folder is a library files directory which contains all helpful library files used by the system. In simple terms, these are helpful files which are used by an application or a command or a process for their proper execution. The commands in /bin or /sbin dynamic library files are located just in this directory.

What should go in a lib directory?

The /lib directory contains kernel modules and those shared library images (the C programming code library) needed to boot the system and run the commands in the root filesystem, ie. by binaries in /bin and /sbin. Libraries are readily identifiable through their filename extension of *. so.

How do I add a module in Rails?

You can include a module in a class in your Rails project by using the include keyword followed by the name of your module.


1 Answers

One use of the lib directory (how I use it most often) is to share code between models to stay DRY. For example, if you are defining a tag_tokens attribute on many different models for use with a tokenizer input, you could put that in "tag_accessor.rb" or something, place it in /lib', and then include it with include TagAccessor. The ruby file might look like:

module TagAccessor   def tag_tokens     tags.map(&:name).join(',')   end    def tag_tokens=(names)     self.tag_ids = names.split(",").uniq   end end 

(This is an example from one of my apps, which is why it's so specific). Then to load the /lib folder in Rails 3, place this in your application.rb:

 config.autoload_paths += %W(#{config.root}/lib) 
like image 180
bricker Avatar answered Sep 29 '22 03:09

bricker