7

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?

user3179047
  • 324
  • 2
  • 12

2 Answers2

9

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
Richard Jordan
  • 8,066
  • 3
  • 39
  • 45
1

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

Community
  • 1
  • 1
arieljuod
  • 15,460
  • 2
  • 25
  • 36
  • I think monkey patching string to give the user a function to manipulate a string available in models and controllers, sounds a little extreme. – Richard Jordan Feb 20 '14 at 02:14
  • it looks like some function reaaaally tied to strings (the name is trim_string!!), why not have that on the string class? I guess that is up to the OP needs – arieljuod Feb 20 '14 at 02:28
  • So, i hear what you're saying - but it's just a method that manipulates strings, and we don't tend to go to the level of monkey patching core classes just because a method manipulates data of that type. It's usually considered best to avoid monkey patching core classes if simpler solutions exist. In this case the user just wants a method to be available to controllers and models, and that is the question. The correct answer to the question is therefore to put shared methods like this in a module in lib, rather than habitually monkey-patching core classes. That'd be my thought, but ymmv. – Richard Jordan Feb 20 '14 at 02:34