-3
  def ads
    @ads = @search.result.recent.completed.paginate(page: params[:page], per_page: 10).limit(10)
  end

  def events
    @events = @search.result.recent.completed.paginate(page: params[:page], per_page: 10).limit(10)
  end

  def pets
    @pets = @search.result.recent.completed.paginate(page: params[:page], per_page: 10).limit(10)
  end

  def companies
    @companies = @search.result.recent.completed.paginate(page: params[:page], per_page: 10).limit(10)
  end

如何将此代码重构到某个范围

4

1 回答 1

1

目前尚不清楚您真正想要存档的内容。在不知道上下文的情况下,我会将您的代码重写为以下内容:

%w( ads events pets companies ).each do |name|
  class_eval <<-END_OF_RUBY, __FILE__, __LINE__ + 1

    def #{name}
      @#{name} = search
    end

  ENF_OF_RUBY
end

private 
  def search
    @search.result.recent.completed.paginate(page: params[:page], per_page: 10).limit(10)
  end
于 2013-10-10T12:50:59.580 回答