how do i check if an object has a particular field?

Is your context a Model: meaning it has the field at all, as in it
exists in the database, or whether the field has been filled in a
form?

Or some other context?

This is a good one. I thought I might be able to help. I tried lots
of things in the console and searched through the api, but everything
yields an error when the object does not have the requested property.
I tried things like blank? and empty? but got the same results. I
looked for something like object.properties to match object.methods
thinking you could test against the result but that does not seem to
exist either. That one would be the most handy, it does exist in the
php reflections.

Are you using this particular property to determine which type of
model the method is receiving? If so, you could use either
object.class == Article or object.is_a?(Article) ... something like
that. Sorry I couldn't be more help than that!

Shouldn't you be able to say:
  object.respond_to?(:complete)

You can also duck-type it:
  class Article
    def complete
      nil # or true depending on your semantics
    end
  end

Then you don't need to check first.

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com

Howdy,

Why can’t #instance_variables work here? It’s not what I would do but looks like it can be used to return an array of an object’s instance variables.

Alternatives:

  • already mentioned #is_a?

  • base class for both objects with appropriate behavior

  • method_missing magic on Article to respond appropriately (could get sticky)

Cheers,
Mel