Pergunta

I want to use an observer to send stuff to Facebook Open Graph.

Roughly, something like:

class ItemObserver < ActiveRecord::Observer
  observe :item
  def after_create(item)
    FbGraph::User.me(item.user.fb_token).og_action!('blah:add', :item => ...)
  end
end

In a controller or a view it's pretty obvious I can use url_for or item_url. But how do I get the URL inside the observer? The observer is definitely the right place to put this code because an item can be created in many places, and putting that call on every action in the controller sounds wrong.

Well, it sounds like a "violation of the MVC", but in that case I think it's needed.

Any ideas how to make it without hacks?

Foi útil?

Solução

Well, including this:

include Rails.application.routes.url_helpers

helps. I'll have an excuse when the trial comes.

More stuff that should be added:

In all environment files (config/environments/ENV_NAME.rb)

routes.default_url_options = { host: "host-for-that-env.com" }

A host must be added because in regular requests the host is figured out from the HTTP request itself.

Wherever you include, add:

include Rails.application.routes.url_helpers
default_url_options[:host] = ::Rails.application.routes.default_url_options[:host]

RSpec:

RSpec.configure do |config|
  config.include Rails.application.routes.url_helpers
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top