Working with classname that is stored in a string

Hi all,

I’m trying to DRY my latest Rails project and have run into a problem
for
which the answer appears to lie in my personal sea of ignorance.

I want to write a helper that will let me set the fields I want to
display
before I start looping.

Basically I wish to pass the class name and an array of fields to be
ignored
to the helper and have it give me an array of the fields I want.

The problem is this, I have no idea how to get Ruby to treat the string
I
pass as a classname. I did some searching and didn’t find anything that
looked like it would solve my problem.

I’d rather not have to create a new instance if I don’t have to.

Thanks,
Glen


“Hey brother Christian with your high and mighty errand, Your actions
speak
so loud, I can’t hear a word you’re saying.”

-Greg Graffin (Bad Religion)

Glen H. wrote:

The problem is this, I have no idea how to get Ruby to treat the string I
pass as a classname. I did some searching and didn’t find anything that
looked like it would solve my problem.

I believe you are looking for const_get.

HTH,
Sebastian

Glen H. wrote:

Hi all,

One thing you can do is not use a string at all, but pass the class name
constant. If you’ve got a class like:

class MyClass

end

then you can do something like:

filtered_fields = filter_my_fields MyClass, [:field1, :field2]

and it works just fine.

Alternatively, you could use an AR extension like this:

class ActiveRecord::Base
def filtered_fields(*fields)
@attributes.reject{|name, value| fields.include?(name.intern)}
end
end

Haven’t run that code, but that should let you do something like
my_ar_instance.filtered_fields(:field1, :field2)

Thanks!

On 8/13/07, Sebastian H. [email protected] wrote:

HTH,
Sebastian

Jabber: [email protected]
ICQ: 205544826


“Hey brother Christian with your high and mighty errand, Your actions
speak
so loud, I can’t hear a word you’re saying.”

-Greg Graffin (Bad Religion)