Dan
Dan

Reputation: 1267

Where to require gems?

I have an ActiveRecord class with a method. I want to refactor this method and divide it into subroutine methods. Method roughly looks like this:

def analyze
  require 'mygem'
  sentences = get_sentences(text)
  sentences.each do |sentence|
    words = get_words(sentence)
    words.each do |word|
      # Use gem
      # For example
      my_gem = MyGem.new
      my_gem.do_something(word)
    end
  end
end

So basically this method takes sentences from the text and then gets all words from it and uses gem on each word. I want to extract words processing into a separate method. Requiring gem and instantiating its' object in extracted method would be inefficient, because it will create instances on each call. So what is the best place to instantiate gem objects? Ideally it would be great to have a global object, which will be created only once on application start.

Upvotes: 0

Views: 55

Answers (1)

Nermin
Nermin

Reputation: 6100

You could specify my_gem as a class object

#...
  private
  def my_gem
    # create class object my_gem, and if not defined define it
    # it will be shared through Class that it resides in 
    @@my_gem ||= MyGem.new
  end
# ...

Upvotes: 1

Related Questions