0

I'd like to set "respond_to" part of action outside of action.

This is an example of how it should work:

def index
  ...
end

def show
  ...
end

response_for :index, :show do
  format.html do
     if empty_records?
       redirect_to root_path
     end
  end

  format.json do
    ...
  end
end

Earlier I used response_for gem for this but it isn't supported anymore. What solutions can you advice? I use Rails 4.2.

Sergei Struk
  • 358
  • 4
  • 12

1 Answers1

0

What about this?

def index
  ...
  return respond
end

def show
  ...
  return respond
end

private

def respond
  respond_to do |format|
    ...
  end
end

I use a similar pattern for building shared success and failure responses with my JSON APIs.

Alex E
  • 466
  • 1
  • 6
  • 17
  • It's good solution, but it's more complicated comparing with code described in the question. Also I'd like to note that I have a big legacy project where described pattern used very often, so it will more easy implement "response_for" method. – Sergei Struk Feb 25 '15 at 16:49