user94154
user94154

Reputation: 16564

Ruby: Dynamically calling available methods raising undefined method (metaprogramming)

I have an Activerecord object called Foo:

Foo.attribute_names.each do |attribute|
  puts Foo.find(:all)[0].method(attribute.to_sym).call
end

Here I'm calling all attributes on this model (ie, querying for each column value). However, sometimes, I'll get an undefined method error.

How can ActiveRecord::Base#attribute_names return an attribute name that when converted into its own method call, raises an undefined method error?

Keep in mind this only happens on certain objects for only certain methods. I can't identify a pattern.

Thank you.

Upvotes: 1

Views: 839

Answers (2)

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79562

The NoMethodError should be telling you which method does not exist for what object. Is it possible that your find returns no record? In that case, [][0] is nil and you will get a NoMethodError for sure.

I would use .fetch(0) instead of [0], and you will get a KeyError if ever there is no element with index 0.

Note: no need for to_sym; all builtin methods accept name methods as strings or symbols (both in 1.8 and 1.9)

Upvotes: 2

JRL
JRL

Reputation: 78003

Maybe something to do with access? Like if a class has an attr_protected attribute, or something along that line. Or for attributes that are not database columns, which have no accessors defined?

Upvotes: 0

Related Questions