Gregory Brown
4/2/2009 2:17:00 PM
On Thu, Apr 2, 2009 at 2:30 AM, Paganoni <noway@fakenullvoid.com> wrote:
> le 01/04/2009 16:47, Rob Biedenharn nous a dit:
>>
>> On Apr 1, 2009, at 9:32 AM, Gregory Brown wrote:
>>
>>> On Wed, Apr 1, 2009 at 9:14 AM, Paganoni <noway@fakenullvoid.com> =A0wr=
ote:
>>>>
>>>> Hi, well subject is self explanatory...
>>>>
>>>> Seems a bit to verbose for me but I don't know any other solution =A0t=
o
>>>> convert
>>>> a string containing a class name to a constant of that class name...
>>>> Excepted rails way : task_class.camelize.constantize which is =A0verbo=
se
>>>> too...
>>>>>
>>>>> Object.const_get("String")
>>>
>>> =3D> String
>>>
>>
>> Or dealing with things like Admin::User or Net::HTTP
>>
>> =A0 # from Jim Weirich (based on email correspondence)
>> =A0 def constantize(camel_cased_word)
>> =A0 =A0 camel_cased_word.
>> =A0 =A0 =A0 sub(/^::/,'').
>> =A0 =A0 =A0 split("::").
>> =A0 =A0 =A0 inject(Object) { |scope, name| scope.const_get(name) }
>> =A0 end
>>
>> It may be more verbose, but it is much safer that plain 'ole eval()
>>
>
> Okay, so nothing less verbose ;-) But thanks for all the answers...
But all of the mentioned suggestions are much better than
eval("ConstantName") in security, performance, and general design.
So if you want something less verbose, just make a method like
C("Whatever") that uses one of those implementations, rather than
forcing Ruby to fire up its parser via eval() just to get a constant.