Search code examples
rubystructprivate

define local/private structs in ruby


I want to define a struct which is local to a file/class. I.e., if I define struct foo in two different files, I want one to be applicable to file a, and one to file b.

Is that doable?


Solution

  • Just assign the struct class to a local variable (i.e. don't give it a class name).

    my_struct = Struct.new(:x)
    

    Caveat

    You can't use the struct definition inside classes/modules/functions/methods in the same file.

    my_struct = Struct.new(:x)
    
    # This works
    my_instance = my_struct.new(123)
    
    class Foo
      def foo
        # This does NOT work
        my_struct.new(123)
      end
    end
    

    Workaround

    You can use the metaprogramming trick called flat scope to mitigate the caveat, but if you decide to do that, you can no longer define methods and classes in the usual way in the whole file, and it's harder to reason about the code because the scope of a method is no longer a clean slate.

    my_struct = Struct.new(:x)
    
    Foo = Class.new do
      define_method :foo do
        # This works, too
        my_struct.new(123)
      end
    end