define local/private structs in ruby

Viewed 51

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?

2 Answers

Just as idea: you can use modules or inner classes

module A
  MyStruct = Struct.new(:x)
end

module B
  MyStruct = Struct.new(:x)
end

or

class A
  MyStruct = Struct.new(:x)
end

class B
  MyStruct = Struct.new(:x)
end

This way you can use your structs independently as A::MyStruct and B::MyStruct

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
Related