all jazz
all jazz

Reputation: 2017

rails application design: static methods

Which would be the most elegant way to define static methods such as "generate_random_string", "generate_random_user_agent", which are called from different libraries?

What are the best practices?

Upvotes: 1

Views: 455

Answers (1)

Kevin Bedell
Kevin Bedell

Reputation: 13404

Best practice as I've seen would include:

  • Put them in a module in /lib/
  • Include them as mixins in the rest of your application code.
  • Make sure they are thoroughly tested with their own rspecs (or whatever test tool you user).

Plan them as if you may at some point want to separate them out into their own gem, or potentially make them available as a service at some point. That doesn't mean design them as separate services from the beginning, but definitely make sure they have no dependencies on any other code in your application.

Some basic code might be something like:

module App::Services

  def generate_random_string
    #  ...
  end   
  def generate_random_user_agent
    #  ...
  end   
end

Then in your model or controller code (or wherever), you could include them like this:

class MyModelClass < ActiveRecord::Base
  include App::Services

  def do_something_here
    foo = random_string
    # whatever...
  end

  def random_string
    generate_random_string
  end

end

Notice I isolated the generate_random_string call in its own method so it can be used in the model class, but potentially be switched out for some other method easily. (This may be a step more than you want to go.)

Upvotes: 2

Related Questions