Ruby on Rails Saturday, August 30, 2014

On 30 August 2014 14:20, Ronald Fischer <lists@ruby-forum.com> wrote:
> Rails 4, Ruby 2
>
> Model has Card and Idiom
> and Idiom belongs_to :card
>
> In my Rails console I have an Idiom i and get the card from it:
>
> c=i.card
>
> => #<Card id: 19, ....>
>
> Now I do:
>
> c.is_a?(Card)
> => false
>
> c.instance_of?(Card)
> => false
>
> Ooops! Why false in both cases?
>
> c.class.name
> => "Card"
> c.class.name==Card.name
> => true
>
> The class name is the same, but the class isn't? Please explain....
>
> And now an explanation why I want to do it:
>
> I have a function which is "overloaded", in that it's single argument
> can be either of a certain clas (in my case, Card (or a subclass of
> it)), or a Fixnum, and I need to distinguish between these cases.
>
> I know that it is not the best style of querying the type of a variable
> at runtime, but the only alternatives I could think of, would be to
> either provide two differently named functions, or have an hash argument
> with two types of keywords, and I don't like both of these solutions.
> Aside from this, I'm really curious to know why is_a? doesn't work
> here.

I *think* it is because it is actually an ActiveRecord Association,
which is converted for you into a Card when you use it (and this may
involve querying the database for example). So in the console it sees
you need to display c.card so it fetches it from the database (if it
has not already been fetched) and displays it as a Card. Apparently
(and I am postulating here) when you do c.class it becomes a card in
order to call the method class on it, but when you pass it to is_a? it
does not (since it does not know until inside is_a? whether it needs
to evaluate it). I may be talking rubbish here in which case someone
more knowledgeable about the internal workings of Rails will jump in.

Colin

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAL%3D0gLu2_3thgHYtOHQDCtP6YQc_fjvo_v%3D-xubL204foqqLXw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment