Re: Is eval the only way?


#1

Thanks Greg!

This works perfectly when run from the console, but generates the
following error when running in my rails testing environment:

NameError (uninitialized constant Kernel::Rate)

Any thoughts? – “Rate” is the class name I’m passing to the method.

: )

Jason

Gregory S. <gsslist+ror@…> writes:

On Wed, Apr 05, 2006 at 05:39:35PM -0400, Jason T. wrote:
} I’m trying to write some methods which use a parameter to
represent a
} Class name.
}
} A very simplistic example:
}
} def foo(class_name, conditions)
} x = class_name.find(:all, :conditions => “#{conditions}”)
} end
}
} Unfortunately, this does not work. The only way around this problem
} that I can think of is to use eval:
[…]
} There’s got to be a better way. – Please help!

def foo(class_name, conditions)
x = Kernel.const_get(class_name).find(:all, :conditions => “#
{conditions}”)
end

} : )
} Jason
–Greg


#2

On Wed, Apr 05, 2006 at 06:55:08PM -0400, Jason T. wrote:
} Thanks Greg!
}
} This works perfectly when run from the console, but generates the
} following error when running in my rails testing environment:
}
} NameError (uninitialized constant Kernel::Rate)
}
} Any thoughts? – “Rate” is the class name I’m passing to the method.

Try this, then:

def foo(class_name, conditions)
x = Kernel.const_get("::#{class_name}").find(:all,
:conditions => “#{conditions}”)
end

} : )
} Jason
–Greg