How to retrieve 'attr_accessor' attribute names?
-
25-12-2020 - |
Question
I am using Ruby on Rails 3.0.9 and I would like to retrieve all attr_accessor
attribute names starting with a specific string. That is,
... in my module I have:
attr_accessor :prefix_attribute_name1,
:prefix_attribute_name2,
:prefix_attribute_name3,
...
:attribute_name1,
:attribute_name2,
...
and I would like to retrieve all attr_accessor
attribute names that starts with the :prefix
string. How can I do that?
Solution
Generally, attr_accessor
just creates accessor methods and doesn't have any particular hooks for reflection like that. If you need such a thing you could either write an extension that wraps around attr_accessor
with alias_method_chain
or you can just make do with this:
(MyClass.instance_methods - Object.instance_methods).grep(/^prefix/).sort
OTHER TIPS
You can grab it using YourClass.instance_methods.select{|i| i.to_s =~ /prefix_/}.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow