user3179047
user3179047

Reputation: 324

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?

Upvotes: 7

Views: 2038

Answers (2)

Richard Jordan
Richard Jordan

Reputation: 8202

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

Upvotes: 9

arieljuod
arieljuod

Reputation: 15838

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

Upvotes: 1

Related Questions