Feature #1400

Please add a method to enumerate fields in OpenStruct

Added by Tomas Pospisek 325 days ago. Updated 177 days ago.

Status :Open Start :04/23/2009
Priority :Normal Due date :
Assigned to :- % Done :

0%

Category :lib
Target version :-

Description

There are two ways to find out what fields an OpenStruct instance has. One is through inspect,
however that returns a String that needs to be parsed.

The second is by white box engineering, looking at OpenStructs source code and seeing that in
fact, it has a hash and getting the keys of that hash...

The second way is faster, more robust, but will break once OpenStruct will be re-engineered...

So I suggest to add an explicit method to return a list of fields in an OpenStruct instance:

--- ostruct.rb.old	2009-04-23 15:26:45.000000000 +0200
+++ ostruct.rb	2009-04-23 15:32:41.000000000 +0200
@@ -110,6 +110,15 @@
     @table.delete name.to_sym
   end
 
+  #
+  # Returns an Array containing the fields of an OpenStruct instance
+  #
+  # p record.fields # -> [:age, :pension, :name]
+  #
+  def fields
+    @table.keys
+  end
+
   InspectKey = :__inspect_key__ # :nodoc:
 
   #

History

04/23/2009 10:37 PM - Tomas Pospisek

A usage example and context for the feature request here: http://www.sourcepole.ch/2009/4/23/what-fields-does-this-openstruct-instance-have

09/19/2009 05:55 AM - Marc-Andre Lafortune

  • Category set to lib
I believe this could be useful.

#members might be a better name, because it is similar in role to Struct.members

The problem is that any new method is a potential compatibility break. #__members__ ?

Also available in: Atom PDF