dimitry_n
dimitry_n

Reputation: 3019

Setting table name in a dynamically-defined class - Rails 4

I am working with a remote database (SQL Server 2008), and have a dynamic class definition, in which I am pointing to a specific table name like so:

  Object.const_set('Foo', Class.new(MyRemoteDB)) do
    self.table_name = ENV['TABLE_NAME']
    def self.go_wild
      ...
    end
  end

but when I try to access any methods defined in my dynamically-generated classes, Rails returns Table doesn't exist.

If I log the table name with self.table_name, I get the conventional plural version of the class name (e.g. foos for class name Foo, or foo_bars for FooBar) instead of the val I set with self.table_name.

Upvotes: 2

Views: 298

Answers (1)

dimitry_n
dimitry_n

Reputation: 3019

Turned out to be the way I am defining the dynamic class. Methods should be defined in a lambda, inside the Object.const_set(...) call:

Object.const_set('Foo', Class.new(MyRemoteDB){
  ...
  self.table_name = ENV['TABLE_NAME']
  ...
})

Upvotes: 2

Related Questions