Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25237

Rails 4 - How to optimize this code

Lets say that I have this code:

class BooksController < ApplicationController

    def action1
        @books = ...
        @books = @books.someaction param1, param2
    end

    def action2
        @books = ...
        @books = @books.someaction param1, param2
    end

    def action3
        @books = ...
        @books = @books.someaction param1, param2
    end

    ...

    def action84
        @books = ...
        @books = @books.someaction param1, param2
    end

I have this action I run on an instance variable quite often. I thought of putting it on an after_action filtering, but that happens after rendering, so that is no good.

How could I optimize this?

Disclaimer: This is a exaggerated case, not a real one. Just trying to make more graphic the problem. I do not have a controller with 84 actions.

Upvotes: 0

Views: 61

Answers (3)

Unixmonkey
Unixmonkey

Reputation: 18784

You can override render just for that particular controller to always do your thing before rendering. Something like this:

class BooksController < ApplicationController

  def action1
    @books = ...
  end

  def action2
    @books = ...
  end

  private

  def render(*args)
    if @books.present? && param1.present? && param2.present?
      @books = @books.someaction param1, param2
    end
    super
  end

end

Upvotes: 2

jkeuhlen
jkeuhlen

Reputation: 4517

I would look at the decent_exposure gem. This should allow you to just do something like:

class BooksController < ApplicationController
    expose(:books) { books.someaction param1, param2 }

    def action1
        books = ...
    end

    def action2
        books = ...
    end

    def action3
        books = ...
    end

    ...

    def action84
        books = ...
    end
end

Upvotes: 1

Yury Lebedev
Yury Lebedev

Reputation: 4005

Just declare a private function in your controller, and use it in your actions:

class BooksController < ApplicationController
  def action1
    @books = ...
    foo
  end

  def action2
    @books = ...
    foo
  end

  def action3
    @books = ...
    foo
  end

  ...

  def action84
    @books = ...
    foo
  end

  private

  def foo
    @books = @books.someaction param1, param2
  end
end

Upvotes: 1

Related Questions