Forum: Ruby Module.private like method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
polypus (Guest)
on 2006-04-26 02:41
i want to make a class method similar to Module.private in that it
should affect subsequent instance method defentions.

class Foo

  def self.rule name
    # code such that all subsequent instance methods
    # defined in subclasses are registered as part of rule 'name'
  end

end

class Bar < Foo

  rule :my_first_rule

  # the following instance methods magically
  # become associated with :my_first_rule

  def foo
  end

  def bar
  end

end

is this possible, or do i need to do some metaprogramming where methods
which belong to a rule start with the rule name say.

thanks
Ryan L. (Guest)
on 2006-04-26 02:55
(Received via mailing list)
On 4/25/06, polypus <removed_email_address@domain.invalid> wrote:
>
> is this possible, or do i need to do some metaprogramming where methods
> which belong to a rule start with the rule name say.

Check this out:

class RulesBased
  def self.rule(rule_name)
    @current_rule = rule_name
  end

  def self.method_added(name)
    puts "Adding method #{name} under rule #@current_rule"
  end
end

class Test < RulesBased
  rule :foo
  def meth1
  end
  def meth2
  end

  rule :bar
  def meth3
  end

  def meth4
  end
end
__END__

Ryan
polypus (Guest)
on 2006-04-26 03:07
thanks many, you rock. i actually tried method_added but must have been
doing something wrong.
Ryan L. (Guest)
on 2006-04-26 03:20
(Received via mailing list)
On 4/25/06, polypus <removed_email_address@domain.invalid> wrote:
> thanks many, you rock. i actually tried method_added but must have been
> doing something wrong.

No problem. Also another option is to code the rules engine as a module:

module RulesBased
  def rule(rule_name)
    @current_rule = rule_name
  end

  def method_added(name)
    puts "Adding method #{name} under rule #@current_rule"
  end
end

class Test
  extend RulesBased

  rule :foo
  def meth1
  end
  def meth2
  end

  rule :bar
  def meth3
  end
  def meth4
  end
end
__END__

This allows you to still subclass from something else.

Ryan
polypus (Guest)
on 2006-05-02 02:05
> This allows you to still subclass from something else.
>
> Ryan


thanks again, i hadn't really considered that for my project, but will
probably end up doing it that way.
This topic is locked and can not be replied to.