mbajur
mbajur

Reputation: 4474

PORO presenter breaks url helpers

I have started creating my rails presenters using a PORO approach. Example presenter resides in app/presenters/band_presenter.rb and here is it's code:

class BandPresenter
  def method_missing(m, *args, &block)
    @band.send(m)
  end

  def initialize(band)
    @band = band
  end

  def thumb_url(size = :large_s)
    @band.images[size.to_s] if @band.images
  end
end

And it works good. However, if i'll use an instance of that presenter in rails url helper methods, it breaks them. For example:

@band = Band.find(1)
= link_to @band.name, band
# => /bands/1

@band = @band.find(1)
@band = BandPresenter.new(@band)
= link_to @band.name, band
# => /%23%3CBandPresenter:0x007f9139c50db0%3E/1

Which seems completely legit. My question is - can i somehow make my presenter support such way of using url helpers?

Upvotes: 1

Views: 677

Answers (1)

mrbrdo
mrbrdo

Reputation: 8258

Try defining a to_param method

class BandPresenter
  def to_param
    @band.id
  end

  def model_name
    @band.model_name
  end
end

Another option that might help is defining respond_to_missing?, see here: http://robots.thoughtbot.com/always-define-respond-to-missing-when-overriding

class BandPresenter
  def respond_to_missing?(method_name, include_private = false)
    @band.respond_to?(method_name, include_private) || super
  end
end

Upvotes: 1

Related Questions