Is eval the only way?


#1

Hi,

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:

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

There’s got to be a better way. – Please help!

: )

Jason


#2

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


#3

On Apr 05, 2006, at 10:39 pm, Jason T. wrote:

: )

Jason

Jason

Try this:

def foo(class_name, conditions)
ObjectSpace.each_object(Class) do |c|
return c.find(:all, :conditions => conditions) if c.name ==
class_name
end
end

You’d have to benchmark it to see which performs better, but it looks
more “Ruby-like” like that.

Ashley


#4

On Apr 05, 2006, at 11:23 pm, Gregory S. wrote:

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

Meh… that beats mine :stuck_out_tongue:

Ashley


#5

def foo(class_name, conditions)
x = Kernel.const_get(class_name).find(:all, :conditions => "#

ive been using Object’s const_get instead of Kernel’s. is there a
difference? and why is there an object and a kernel if not?


#6

On Thu, Apr 06, 2006 at 02:08:21AM +0200, carmen wrote:
}
} >> def foo(class_name, conditions)
} >> x = Kernel.const_get(class_name).find(:all, :conditions => "#
}
} ive been using Object’s const_get instead of Kernel’s. is there a
} difference? and why is there an object and a kernel if not?

No, there isn’t:

irb(main):001:0> Object.included_modules
=> [Kernel]
irb(main):002:0>

–Greg


#7

On 4/5/06, Jason T. removed_email_address@domain.invalid wrote:

Unfortunately, this does not work. The only way around this problem
that I can think of is to use eval:

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

There’s got to be a better way. – Please help!

Inside Rails, you can do:
x = class_name.constantize.find(:all, :conditions => “#{conditions}”)

constantize is a more-readable shortcut for the const_get business.