class constants

If I have:

@name = 'users'

And I want to do

@name.singularize.camelize.constantize.find(1)

It seems I cannot do so unless the constant User is already present in ObjectSpace. Is there a dynamic way around this?

I'm embarrassed to admit this is my best idea so far:

name = @name.singularize open( "#{ RAILS_ROOT }/tmp/cache/#{ name }.rb", 'w' ) do |f|   f.puts "class #{ name.camelize } < ActiveRecord::Base\n set_table_name \"#{ @name }\"\nend\n" end require "#{ RAILS_ROOT }/tmp/cache/#{ name }.rb" name = name.camelize.constantize

It works fine but then I have to do:

Dir.glob("#{RAILS_ROOT}/app/models/*.rb").each { |f| require f }

at the end to restore sanity to my Rails app.

I realize I can add some more checks to see if the faked model file is already there and all, but please someone tell me there's a better way.

That works fine if you have the model file already.

Please re-read my post.. or not.

If I have:

@name = 'users'

And I want to do

@name.singularize.camelize.constantize.find(1)

It seems I cannot do so unless the constant User is already present in ObjectSpace. Is there a dynamic way around this?

Is there no constant just because the user.rb file has not been loaded or is there no user.rb file If the former it should just work, if the latter:

klass = Class.new(ActiveRecord::Base) Object.const_set name.camelize, klass klass.reset_table_name

klass.find :first

Fred

If I have:

@name = 'users'

And I want to do

@name.singularize.camelize.constantize.find(1)

It seems I cannot do so unless the constant User is already present in ObjectSpace. Is there a dynamic way around this?

I'm embarrassed to admit this is my best idea so far:

name = @name.singularize open( "#{ RAILS_ROOT }/tmp/cache/#{ name }.rb", 'w' ) do |f|   f.puts "class #{ name.camelize } < ActiveRecord::Base\n set_table_name \"#{ @name }\"\nend\n" end require "#{ RAILS_ROOT }/tmp/cache/#{ name }.rb" name = name.camelize.constantize

It works fine but then I have to do:

Dir.glob("#{RAILS_ROOT}/app/models/*.rb").each { |f| require f }

at the end to restore sanity to my Rails app.

I realize I can add some more checks to see if the faked model file is already there and all, but please someone tell me there's a better way.

If I understand correctly, you are looking for a way to wrap an ActiveRecord model around a DB table given the name of the DB table without (necessarily) creating a .rb file for it a priori. If that's accurate, I think you want this:

name = Object.const_set(@name.singularize.camelize,   Class.new(ActiveRecord::Base))

Greg Donald

--Greg

I did reread your post, which is why I deleted my message about 30 seconds after I posted it. :slight_smile:

///ark

That's it. Thanks.