Rails 4助手类

时间:2014-11-13 20:10:01

标签: ruby-on-rails

我正在努力寻找在我的Rails 4应用程序中实现以下类的最佳方法。我只需要在一个控制器中使用这个类,而且它非常冗长。

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

我已经查看了辅助模块,但我知道它们适用于视图逻辑。

我对将此逻辑放入我的application_controller.rb犹豫不决,因为就像我说的那样,我只在我的一个控制器中使用它。

我已经尝试将此课程放在lib目录中,但没有成功。我跟着this SO post,但我一直得到:undefined method 'my_method' for <MainController>

1 个答案:

答案 0 :(得分:1)

app / controllers / concerns / 目录中创建一个ActiveSupport::Concern的模块,让我们称之为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

ThatOneController

中使用它
class ThatOneController < ApplicationController
  include YelpSearcher
  # more code here..
end

更多阅读topic here