Reputation: 110980
I have the following Observer:
class NewsFeedObserver < ActiveRecord::Observer
observe :photo, :comment
def after_create(record)
end
end
What'd I'd like to learn how to do is add a SWITCH/IF statement in the after_create, so I know which model was created
Something like:
after_create(record)
switch model_type
case "photo"
do some stuff
case "comment"
do some other stuff
end
Or easier to visualize:
if record == 'Photo'
How can I take record, and determine the model name?
Upvotes: 1
Views: 1763
Reputation: 77778
In a comment, I notice you found this works using record.class.name
but that's not very idiomatic Ruby. The Ruby case
statement uses ===
for comparison which will work perfectly for you if you implement it properly.
class NewsFeedObserver < ActiveRecord::Observer
observe :photo, :comment
def after_create(record)
case record
when Photo
# do photo stuff
when Comment
# do comment stuff
else
# do default stuff
end
end
end
This essentially converts to:
if Photo === record
# do photo stuff
elsif Comment === record
# do comment stuff
else
# do default stuff
end
I advise you to note the following:
class Sample
end
s = Sample.new
Foo === s # true uses Class#===
s === Foo # false uses Object#===
===
is implemented differently in Class
and Object
Upvotes: 3
Reputation: 15492
You need to setup separate observers for separate models
So for User => UserObserver , Photo => PhotoObserver
You need to tell the rails app what observers to use, that you specify in config/environment.rb
Atleast this is the standard way. For more details
http://guides.rubyonrails.org/active_record_validations_callbacks.html#observers
Upvotes: 1