phpete
phpete

Reputation: 316

Rails 4 helper class

I'm struggling to find the best way to implement the following class in my Rails 4 application. I only need to use this class in one controller and it's very lengthy.

class Yelp
   ##
   # Performs query on Yelp Search or Business API
   ##
   def query(business, term = 'lunch', cuisine = 'restaurants', limit = restaurant_limit, location = get_city)
     # ..
   end

   ##
   # Extracts a list of cuisines formatted for the view
   # @param  array of restaurant objects
   # @return hash of cuisines
   ##
   def get_cuisines(restaurants)
      # ..
   end

   ##
   # Creates [non-ActiveRecord] model objects from an array of restaurant data
   # @param  array of hashes containing restaurant data
   # @return array of objects containing restaurant data
   ##
   def parse_restaurants(restaurants)
      # ..
   end

   ##
   # Creates Gmaps pins from restaurant objects
   # @param  array of restaurant objects to become pins
   # @return Gmaps pins
   ##
   def get_pins(restaurants)
      # ..
   end
end

I've looked into helper modules but I understand they are for view logic.

I'm hesitant to put this logic into my application_controller.rb because, like I said, I only use it in one of my controllers.

I've tried putting this class in the lib directory but had no success. I followed this SO post but I keep getting: undefined method 'my_method' for <MainController>.

Upvotes: 0

Views: 81

Answers (1)

Surya
Surya

Reputation: 15992

Create a module with ActiveSupport::Concern in your app/controllers/concerns/ directory, let's call it yelp_searcher.rb:

module YelpSearcher
  extend ActiveSupport::Concern
  ##
  # Performs query on Yelp Search or Business API
  ##
  def query(business, term = 'lunch', cuisine = 'restaurants', limit = restaurant_limit, location = get_city)
    # ..
  end

  ##
  # Extracts a list of cuisines formatted for the view
  # @param  array of restaurant objects
  # @return hash of cuisines
  ##
  def get_cuisines(restaurants)
     # ..
  end

  ##
  # Creates [non-ActiveRecord] model objects from an array of restaurant data
  # @param  array of hashes containing restaurant data
  # @return array of objects containing restaurant data
  ##
  def parse_restaurants(restaurants)
     # ..
  end

  ##
  # Creates Gmaps pins from restaurant objects
  # @param  array of restaurant objects to become pins
  # @return Gmaps pins
  ##
  def get_pins(restaurants)
     # ..
  end
end

Use it in your ThatOneController:

class ThatOneController < ApplicationController
  include YelpSearcher
  # more code here..
end

More reading on the topic here.

Upvotes: 1

Related Questions