Title: instance_of? returning unexpected result
Tags: ruby-on-rails;ruby;ruby-on-rails-3;ruby-on-rails-3.1
Question: I have an observer following two models:
class MyObserver < ActiveRecor75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0Observer
observe :my_first_model, :my_second_model
def after_create(record)
x = if record.instance_of?(MyFirstModel)
# x is set to one thing
elsif record.instance_of?(MySecondModel)
# x is set to another thing
end
# use x in a common way
As you can see, I'm setting x to something different depending on the model whose creation is being observed.
I'm getting unexpected results using instance_of? and kind_of?. For instance, I can do Rails.logger.debug record.class.name and see MyFirstModel but record.instance_of?(MyFirstModel) returns false.
Has anyone come across this before? I'm using Ruby 1.9.3 and Rails 3.1.
In the mean time, I'm going to resort to record.class.name.inquiry.MyFirstModel? or something similar.


Here is another answer: Use a case statement for this.
def after_create(record)
x = case record
when MyFirstModel
# x is set to one thing
when MySecondModel
# x is set to another thing
else ; return false
# use x in a common way
Comment for this answer: Thanks for the answer, @gg_s. I didn't know that you could use a class name in a case statement like that so something new learned. Sadly, it didn't solve the problem and `record` isn't being identified correctly.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:02/12/12', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<ruby-on-rails><ruby><ruby-on-rails-3><ruby-on-rails-3.1>', 'Title': 'instance_of? returning unexpected result', 'ViewCount': 131, 'id': 9253024, 'user_AboutMe': None, 'user_AccountId': 116590.0, 'user_DisplayName': 'tristanm', 'user_Reputation': 3337.0, 'user_Views': 123.0, 'user_id': 305668.0}}