Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, where to put useful functions for both controllers and models

Suppose I have a function trim_string(string) that I want to use throughout my Rails app, in both a model and a controller. If I put it in application helper, it gets into the controller. But application helper isn't required from within models typically. So where do you put common code that you'd want to use in both models and controllers?

like image 242
user3179047 Avatar asked Feb 20 '14 01:02

user3179047


2 Answers

In answer to the specific question "where do you put common code that you'd want to use in both models and controllers?":

Put it in the lib folder. Files in the lib folder will be loaded and modules therein will be available.

In more detail, using the specific example in the question:

# lib/my_utilities.rb

module MyUtilities
  def trim_string(string)
    do_something
  end    
end

Then in controller or model where you want this:

# models/foo.rb

require 'my_utilities'

class Foo < ActiveRecord::Base
  include MyUtilities

  def foo(a_string)
    trim_string(a_string)
    do_more_stuff
  end
end

# controllers/foos_controller.rb

require 'my_utilities'

class FoosController < ApplicationController

  include MyUtilities

  def show
    @foo = Foo.find(params[:id])
    @foo_name = trim_string(@foo.name)
  end
end
like image 50
Richard Jordan Avatar answered Sep 21 '22 08:09

Richard Jordan


It looks like you want to have a method on the String class to "trim" itself better than a trim_string function, right? can't you use the strip method? http://www.ruby-doc.org/core-2.1.0/String.html#method-i-strip

You can add new methods to the string class on an initializer, check this In Rails, how to add a new method to String class?

class String
  def trim
    do_something_and_return_that
  end

  def trim!
    do_something_on_itself
  end
end

That way you can do:

s = '  with spaces '
another_s = s.trim #trim and save to another
s.trim! #trim itself

but check the String class, it looks like you already have what you need there

like image 25
arieljuod Avatar answered Sep 19 '22 08:09

arieljuod