Skip to content

Instantly share code, notes, and snippets.

@rlogwood
Last active May 14, 2021 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rlogwood/b29b1391259b33215664155205583c10 to your computer and use it in GitHub Desktop.
Save rlogwood/b29b1391259b33215664155205583c10 to your computer and use it in GitHub Desktop.
Rails controller strategy pattern via controller.instance_eval
class MyController < ApplicationController
# ...
def search_all
return unless (@search_phrase = search_phrase_or_redirect)
doc_types = %w[Episode ForumPost Series]
notification_payload = { action: "search_all", search_phrase: @search_phrase,
doc_types: doc_types, pagy_limit: RESULT_PAGE_SIZE }
ActiveSupport::Notifications.instrument('search_render', notification_payload) do
Current.search_strategy.search_all(self, @search_phrase, doc_types, RESULT_PAGE_SIZE)
end
end
# ...
end
class MyStrategy
# ...
def search_all(controller, search_phrase, doc_types, limit)
doc_search_results = find_docs(search_phrase, doc_types)
controller.instance_eval do
@pagy, @search_results = pagy(doc_search_results, limit: limit)
render "my_strategy/search_results", locals: { search_phrase: @search_phrase, search_results: @search_results, pagy: @pagy }
end
end
# ...
end
@t27duck
Copy link

t27duck commented May 14, 2021

class MyController < ApplicationController
  # ...
  def search_all
    return unless (@search_phrase = search_phrase_or_redirect)

    doc_types = %w[Episode ForumPost Series]
    notification_payload = { action: "search_all", search_phrase: @search_phrase,
                             doc_types: doc_types, pagy_limit: RESULT_PAGE_SIZE }

    ActiveSupport::Notifications.instrument('search_render', notification_payload) do
      results, path = Current.search_strategy.search_all(self, @search_phrase, doc_types)
      @pagy, @search_results = pagy(results, limit: RESULT_PAGE_SIZE)
      render "#{path}/search_results", locals: { search_phrase: @search_phrase, search_results: @search_results, pagy: @pagy }
    end
  end
  # ...
end


class MyStrategy
  # ... 
  def search_all(search_phrase, doc_types)
     [find_docs(search_phrase, doc_types), SOMETHING_THAT_SAYS_WHICH_PATH]
  end
  # ...
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment