[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

metaprogramming question, alternatives to "class ..."

Kevin McConnell

9/28/2004 8:18:00 PM

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 :-)

Cheers,
Kevin
3 Answers

Florian Gross

9/28/2004 8:24:00 PM

0

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

Kevin McConnell

9/28/2004 8:35:00 PM

0

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

Florian Gross

9/28/2004 8:48:00 PM

0

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