2

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.

2 Answers 2

1
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
Sign up to request clarification or add additional context in comments.

4 Comments

Ohh, thats seems to be pretty in fashion of DRY. Thank you for your answer. Is this common? Is there any limitations in using this?
It's a little obtuse. If you came across the functionally equivalent version that I posted at the end of my answer, would you have come here to ask this question? Probably not, because it would have been obvious.
Yeah, you're right. Thank you for clarification. I already tested it.
The class Note; attr_accessor… version isn't quite equivalent. It doesn't get the hashlike behavior of a Struct.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.