Forum: Ruby on Rails Re: Is eval the only way?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jason T. (Guest)
on 2006-04-06 02:56
(Received via mailing list)
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
 >
Gregory S. (Guest)
on 2006-04-06 04:36
(Received via mailing list)
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
This topic is locked and can not be replied to.