Forum: Ruby Metaprogramming question

0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2016-12-22 14:17
To get experience with metaprogramming, I tried to solve the following
problem:

I want for this excercise to write a method, which works similarily to
methods such as attr_accessor etc., and can be used like this:

class Foo

  define_seq :a,:b,:c

  def a; ...; end
  def b; ...; end
  def c; ...; end

end

The effect should be, that define_seq defines an instance method named
do_seq, which, when called, invokes the methods a, b, c in sequence.

I made two implementations of this feature, but I don't like both of
them very much. Here they are:

(1) This one works exactly as it should:

class Object

  def self.define_seq(*args)
    define_method(:do_seq) do
      args.each do |arg|
        public_send(arg)
      end
    end
  end

end

(2) This one requires, that I the module will be mixed into my class:

module Seq

  def define_seq(*args)
    define_method(:do_seq) do
      args.each do |arg|
        public_send(arg)
      end
    end
  end

end

The first solution has the disadvantage, that I have to monkey-patch the
class Object - something I try to avoid if possible. The second solution
is inconvenient to use, because I have to write two lines,

    extend Seq
    define_seq :a,:b,:c

Could someone suggest a third possibility to implement this?
3cf6fa0fff2146ac687c8ba9d9022172?d=identicon&s=25 Sven S. (sunito)
on 2017-01-01 22:40
Hi Ronald,

why don't you "monkey-patch" just Module?
Wouldn't this be enough?
Or am I missing something?

Have a nice year
Sven
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2017-01-02 08:28
In my first solution, the monkey-patch needs to be done in a superclass
of the class where I want to use this feature. Since most classes don't
have Module as superclass, I can't do it in Module.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.