Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put code snippets in Rails?

I have this code snippets that generates a signature for POSTs. The detail of it is not important, but what I want to know is: since it is not a model-related chunk of code, it really can be use anywhere: in controllers, in models, in view helpers; even in views. So I am unsure where and, even bigger of a problem, how to activate the use of it once I place it in some location.

Is it what those "require" statements are all about? That you can acquire some functionality through a "require" statement in the current file you are working on?

Just so that we have an example to talk about, say, I have a little snippet of code that does cubing:

def cube_it(num)
  num**3
end

I know that I will be using it in various places across the application, so where should I put it? and when I do need to use it, how can I "summon" it?

Thank You

like image 272
Nik So Avatar asked May 21 '10 05:05

Nik So


People also ask

Where do you store code snippets?

There are various ways you can store a code snippet, either by keeping it in a GitHub repository or can use a smart code snippet manager, like Codiga's Coding Assistant. Coding Assistant allows you to store and reuse code snippets.

How do I add a code snippets to my website?

This is quick and easy to do using a tool like: http://htmlencode.net/ Use <pre><code> tags to surround your code. For the <pre> tag you can optionally add class=”line-numbers”. This will add line numbers to your code and these line numbers will not be copied if students copy and paste snippets.


2 Answers

I would suggest putting your code inside a module named Math in lib/math.rb.

math.rb
module Math
  class << self
    def cube_it(num)
      num*3
    end
  end
end

You don't need any require statements with this (rails does it for you) and you can easily call it with Math.cube_it("Hi").

There are other ways of adding code to a rails application, but this is the best way.

like image 165
Samuel Avatar answered Sep 29 '22 16:09

Samuel


Rails autoloads modules and classes when they are first used. You can put your function into a module (or class) and put the file into the lib directory in your application. require statements aren't used in Rails apps often.

like image 41
Alex Korban Avatar answered Sep 29 '22 15:09

Alex Korban