Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Attributing Methods [duplicate]

I am looking for a way to categorize or attributize methods in classes/modules. I need to tag methods in a class, so when the ruby script launches, I can use reflection to identify modules and classes which contain methods that have a certain tag.

C# has something like this, which is referred to as attributes, although the term attributes means something different in ruby. I was curious if this functionality existed.

like image 443
MobileOverlord Avatar asked Dec 06 '25 05:12

MobileOverlord


1 Answers

You can list methods using .methods

Example

class TestClass
  def method1
  end

  def tag_method2
  end

  def method3
  end
end

test = TestClass.new

test.methods
# => [:method1, :tag_method2, :method3, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, ... ]

and you can do a select to filter

test.methods.select{|m| m.to_s.include? "tag"}
# => [:tag_method2]

All class that inherit from Object can execute .methods

http://ruby-doc.org/core-1.9.3/Object.html#method-i-methods

like image 98
dimartiro Avatar answered Dec 09 '25 19:12

dimartiro