From: Robert Dober Date: 2007-05-07T00:25:15+09:00 Subject: Re: how to define a method template On 5/6/07, Robert Klemme wrote: > On 06.05.2007 13:14, Robert Dober wrote: > > On 5/6/07, Robert Klemme wrote: > >> On 06.05.2007 10:36, Nanyang Zhan wrote: > >> > Forgive me for the nonstandard words. I will describe my problem in > >> > details: > >> > I am doing a rails app, and met a ruby problem. > >> > Inside a model class, I will need to write these codes for "apple" > >> > def apple_attr > >> > apples.collect {|o| o.name}.join(" ") > >> > end > >> > > >> > def apple_attr=(str) > >> > @apple = str > >> > end > >> > > >> > def save_apple > >> > #lots of codes > >> > end > >> > > >> > then banana, cat, dog.. each will have a copy of above codes. They are > >> > the same, except replacing the word "apple" with "banana", "cat", > >> > "dog".... > >> > > >> > I know there is a way to put these code in to a module, then mixin the > >> > module with current class, after that, you just need to call a method > >> > (like setup_methods(:apple); setup_methods(:dog)...), instead of typing > >> > the repeated code. > >> > > >> > Would any one tell me how to do it? > >> > >> Why not create all the methods on the fly? Like > >> > >> class Foo > >> def setup_methods(sym) > >> cl = class < >> cl.class_eval do > >> attr_accessor sym > >> end > >> cl.class_eval "def #{sym}_save() puts 'saving #{sym}' end" > >> end > >> end > > Robert I have understood the setup a little bit differently, was it > > not on the class base that OP wanted his methods? > > Maybe. His statement seems to be a bit contradictory. First he talks > about all these methods being there. Then he mentions some method > setup_methods which I believe is to create those methods. But you're > right, could also be a class method (like attr_accessor). OP, what do > you want - Robert's solution or Robert's solution? :-) Difficult decision LOL > > Kind regards > > robert > > -- You see things; and you say Why? But I dream things that never were; and I say Why not? -- George Bernard Shaw