Metaprogramming question, alternatives to "class ..."

Folks,

I'm starting to dabble in using some of Ruby's metaprogramming features, in an effort to use actual code in place of configuration files. It's got me to wondering if there's a way to define a method to take the place of a class declaration.

In other words, say I have something like this:

class AddressDataSource < DataSourceBase
   field :name, "customer_name"
   field :address, "cust_addr"
end

....is there any cunning trickery that would allow me to do this:

datasource AddressDataSource
   field :name, "customer_name"
   field :address, "cust_addr"
end

I couldn't think of a way to have a method than can parse up until the matching "end". But, there's a lot of stuff I read here that I wouldn't have thought of myself :slight_smile:

Cheers,
   Kevin

Kevin McConnell wrote:

In other words, say I have something like this:

class AddressDataSource < DataSourceBase
  field :name, "customer_name"
  field :address, "cust_addr"
end

...is there any cunning trickery that would allow me to do this:

datasource AddressDataSource
  field :name, "customer_name"
  field :address, "cust_addr"
end

You can have this:

datasource(:AddressDataSource) do
   field :name, "customer_name"
   field :address, "cust_addr"
end

With this:

def datasource(name, &block)
   Object.const_set(name, Class.new(DataSourceBase, &block))
end

Cheers,
  Kevin

Regards,
Florian Gross

Florian Gross wrote:

You can have this:

datasource(:AddressDataSource) do
  field :name, "customer_name"
  field :address, "cust_addr"
end

With this:

def datasource(name, &block)
  Object.const_set(name, Class.new(DataSourceBase, &block))
end

That's exactly what I was looking for, thanks.

Cheers,
   Kevin

Kevin McConnell wrote:

[snip]

That's exactly what I was looking for, thanks.

Small correction:

def datasource(name, &block)
   module = Module.nesting.first || Object
   module.const_set(name, Class.new(DataSourceBase, &block))
end

That will fix this case:

module X
   datasource(:AddressDataSource) do
     ...
   end
end

Cheers,
  Kevin

Regards,
Florian Gross