# Creating trivial classes with Struct.new (adding constraints

**URL:** <https://www.ruby-forum.com/t/creating-trivial-classes-with-struct-new-adding-constraints/194857>\
**Category:** Ruby\
**Created:** [September 12, 2010, 3:48pm UTC](https://www.ruby-forum.com/t/creating-trivial-classes-with-struct-new-adding-constraints/194857 "2010-09-12T15:48:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sentinel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/fbc32d/32.png) [@sentinel](https://www.ruby-forum.com/u/sentinel)\
**Post date:** [September 12, 2010, 3:48pm UTC](https://www.ruby-forum.com/t/creating-trivial-classes-with-struct-new-adding-constraints/194857/1 "2010-09-12T15:48:31Z")

</div>

I’d like to use this form for making small classes rather than hand  
coding my “beans”.

ActionEvent = Struct.new(:source, :id, :text) do  
def xxx … end  
end

However, is there anyway I can add some constraints, such as:

- source (some of the fields) must not be nil.
- no changing values after creation, unless there’s a method provided

Essentially, the fields should correspond to attr\_reader and not  
attr\_accessor.  
Have i lost the open purpose of this form in my requirement.

I was reading this article about it:  
[http://blog.grayproductions.net/articles/all\_about\_struct](http://blog.grayproductions.net/articles/all_about_struct) (Thx to JEG).

---

<div class="post-metadata">

**Author:** ![sentinel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/fbc32d/32.png) [@sentinel](https://www.ruby-forum.com/u/sentinel)\
**Post date:** [September 13, 2010, 5:38am UTC](https://www.ruby-forum.com/t/creating-trivial-classes-with-struct-new-adding-constraints/194857/2 "2010-09-13T05:38:49Z")

</div>

On Sep 12, 7:49 am, Rahul K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Essentially, the fields should correspond to attr\_reader and not  
> attr\_accessor.  
> Have i lost the open purpose of this form in my requirement.

> **[GitHub - ahoward/openobject: a simple property based container that's much...](https://github.com/ahoward/openobject)**
>
> a simple property based container that's much more capable than a blankslate but far less polluted than ruby's built-in OpenStruct - GitHub - ahoward/openobject: a simple property based c...

-a
