Question

I have found very rare(to me) line of code in one of ours old repositories. Following code aws part of PoC application for simple Note taking app. Nevertheless, these two lines in model folder surprised me:

class Note < Struct.new(:title, :due_to, :body, :self_url, :image_url) 
end

I was looking up this technique for a while and haven't really found some valuable source of information about this implementaiton.

Can someone help me to better understand this? I think that this kind usage of Struct just creating new object which inherits from Struct. But I don't see the benefits here.

Was it helpful?

Solution

Struct.new(:title, :due_to, :body, :self_url, :image_url)
#=> #<Class:0x007fed5b1859c0>

Check that out, Struct.new returns a class. A class that can create instances with getters and setters for some named fields. And, of course, any class can be inherited from.

So this is simply a slightly odd way of defining a list of instance properties in the class declaration.

Which means this is funcationally the same as:

class Note
  attr_accessor :title, :due_to, :body, :self_url, :image_url
end

OTHER TIPS

That line of code is an idiosyncratic way of declaring a Struct-based class. The more normal way of doing it is (in my experience):

Note = Struct.new(:title, :due_to, :body, :self_url, :image_url) do
  …
end

Struct classes get automatic accessors and an initialize method for their named attributes, as well as a Hash-like interface that includes [] and []= for getting and setting the named attributes, each_pair for the attributes and a few other goodies. Structs are very nice for POD-ish types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top