# Null object pattern

**URL:** <https://www.ruby-forum.com/t/null-object-pattern/162862>\
**Category:** Rails\
**Created:** [March 14, 2009, 6:08pm UTC](https://www.ruby-forum.com/t/null-object-pattern/162862 "2009-03-14T18:08:53Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 14, 2009, 6:08pm UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/1 "2009-03-14T18:08:53Z")

</div>

I am trying to create a null object in my application. I would like to  
assigned a null user object for anonymous/ mot-logged-in user, i.e. if  
session variable has nil data.

In my User model, I have created a subclass like this:  
class UnassignedUser \< User

def save  
false  
end

def update  
false  
end

def username  
“Unassigned”  
end

def county\_id  
“-999”  
end

def role\_id  
“5”  
end  
end

When I go to console to try out this model following is the output:

> > UnassignedUser.new  
> > NameError: uninitialized constant UnassignedUser  
> > from  
> > /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active\_support/dependencies.rb:278:in  
> > `load_missing_constant' from /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:467:in`const\_missing’  
> > from  
> > /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active\_support/dependencies.rb:479:in  
> > `const\_missing’  
> > from (irb):1

> > User.new  
> > =\> #\<User id: nil, username: nil, section\_id: nil, password\_hash: nil,  
> > password\_salt: nil, role\_id: nil, member\_number: nil, tm\_zone\_info: nil,  
> > region\_id: nil\>

> > UnassignedUser.new  
> > =\> #\<UnassignedUser id: nil, username: nil, section\_id: nil,  
> > password\_hash: nil, password\_salt: nil, role\_id: nil, member\_number:  
> > nil, tm\_zone\_info: nil, region\_id: nil\>

If I create user object first and then unassigneduser then it does not  
give any error (although it is not doing what I intend to do).

Can anyone please elaborate on how to use null object pattern?

Thanks,  
CS.

---

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 14, 2009, 6:36pm UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/2 "2009-03-14T18:36:54Z")

</div>

If you have a construct like this (all in the same file):

# app/models/user.rb

class User \< ActiveRecord::Base  
# …  
end

class UnassignedUser \< User  
def self.shout  
puts “yeah”  
end  
end

script/console will behave like this:

> > UnassignedUser.shout  
> > NameError: uninitialized constant UnassignedUser (…)  
> > User  
> > =\> User(id: integer, login: string, email: string, password: string,  
> > created\_at: datetime, updated\_at: datetime)  
> > UnassignedUser.shout  
> > yeah  
> > =\> nil

UnassignedUser gets only loaded when User is loaded. put it in its own  
file and maybe add:  
self.abstract\_class = true

other than that you can load it whenever you want via include or  
require.

---

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 14, 2009, 9:30pm UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/3 "2009-03-14T21:30:00Z")

</div>

MaD wrote:

> If you have a construct like this (all in the same file):
> 
> # app/models/user.rb
> 
> class User \< ActiveRecord::Base  
> # …  
> end
> 
> class UnassignedUser \< User  
> def self.shout  
> puts “yeah”  
> end  
> end
> 
> script/console will behave like this:
> 
> > > UnassignedUser.shout  
> > > NameError: uninitialized constant UnassignedUser (…)  
> > > User  
> > > =\> User(id: integer, login: string, email: string, password: string,  
> > > created\_at: datetime, updated\_at: datetime)  
> > > UnassignedUser.shout  
> > > yeah  
> > > =\> nil
> 
> UnassignedUser gets only loaded when User is loaded. put it in its own  
> file and maybe add:  
> self.abstract\_class = true

Separate file in the model directory?

My objective is to avoid nil object errors when no user is logged in -  
i.e. when session[:user] is nil.

However, I still need to call some instance methods on this object.

Please suggest me how can I do this?

> other than that you can load it whenever you want via include or  
> require.

---

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 15, 2009, 12:30am UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/4 "2009-03-15T00:30:14Z")

</div>

Hi Carlos,

On Sat, 2009-03-14 at 21:30 +0100, Carlos S. wrote:

> My objective is to avoid nil object errors when no user is logged in -  
> i.e. when session[:user] is nil.
> 
> However, I still need to call some instance methods on this object.
> 
> Please suggest me how can I do this?

I’m thinkin’ I must be missin’ somethin’. Why can’t you use…

do\_somethin’ unless session[:user].nil?

?

Best regards,  
Bill

---

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 15, 2009, 1:02am UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/5 "2009-03-15T01:02:30Z")

</div>

On Mar 14, 8:30 pm, Carlos S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> MaD wrote:
> 
> > UnassignedUser gets only loaded when User is loaded. put it in its own  
> > file and maybe add:  
> > self.abstract\_class = true
> 
> Separate file in the model directory?

Yes. The think to understand is that if your app hits the constant  
Foo, rails will try and load foo.rb hoping that it defines Foo. If  
there is no such foo.rb because Foo is in fact declared in bar.rb then  
this don’t work.  
You need to either put things where rails will find them automatically  
or explicitly require them (using require\_dependency)

Fred

---

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 15, 2009, 1:29am UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/6 "2009-03-15T01:29:26Z")

</div>

I put UnassignedUser class in a separate file and added  
self.abstract\_class = true and also included requirement of User class.  
Still same error.

Any more guidelines?

CS.

Frederick C. wrote:

> On Mar 14, 8:30ï¿½pm, Carlos S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
> wrote:
> 
> > MaD wrote:
> > 
> > > UnassignedUser gets only loaded when User is loaded. put it in its own  
> > > file and maybe add:  
> > > ï¿½ self.abstract\_class = true
> > 
> > Separate file in the model directory?
> 
> Yes. The think to understand is that if your app hits the constant  
> Foo, rails will try and load foo.rb hoping that it defines Foo. If  
> there is no such foo.rb because Foo is in fact declared in bar.rb then  
> this don’t work.  
> You need to either put things where rails will find them automatically  
> or explicitly require them (using require\_dependency)
> 
> Fred

---

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 15, 2009, 4:53am UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/7 "2009-03-15T04:53:57Z")

</div>

It worked..  
Had a typo.. ☹

Thanks for the help.

Carlos S. wrote:

> I put UnassignedUser class in a separate file and added  
> self.abstract\_class = true and also included requirement of User class.  
> Still same error.
> 
> Any more guidelines?
> 
> CS.
> 
> Frederick C. wrote:
> 
> > On Mar 14, 8:30ï¿½pm, Carlos S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
> > wrote:
> > 
> > > MaD wrote:
> > > 
> > > > UnassignedUser gets only loaded when User is loaded. put it in its own  
> > > > file and maybe add:  
> > > > ï¿½ self.abstract\_class = true
> > > 
> > > Separate file in the model directory?
> > 
> > Yes. The think to understand is that if your app hits the constant  
> > Foo, rails will try and load foo.rb hoping that it defines Foo. If  
> > there is no such foo.rb because Foo is in fact declared in bar.rb then  
> > this don’t work.  
> > You need to either put things where rails will find them automatically  
> > or explicitly require them (using require\_dependency)
> > 
> > Fred

---

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 15, 2009, 1:49pm UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/8 "2009-03-15T13:49:47Z")

</div>

Hello Carlos,  
I am glad it worked for you. Access control is a fundamental  
requirement along with authentication. Jim N.'s Bort which is  
available on Github, packages Role Requirements written by Tim H.  
along with Restful Authentication for creating a baseline  
application. Tim has done an excellent job of implementing a  
“minimal” authorization plugin. I am using Bort to develop my own  
toolkit for creating applications.  
I looked at the article that you list above. It is very well written  
and very nice to learn from. The key thing missing from it is that it  
fails to deal with Roles and instead deals directly with users. I  
think a minimal layer of roles between users and controllers is a key  
requirement.  
I am not saying that Role Requirement is the only plugin that  
addresses it. It is just that it packaged with Bort which has other  
key plugins in addition to Restful Authentication and Role  
Requirements. Gets the job done.  
So instead of saying session[:current\_user].nil? you may want to say  
[:current\_user].has\_role?(‘anonymous’) for example. See the method  
“has\_role?” provided by Role Requirement? That is the key in my  
opinion.  
I may be wrong, but that is where I am going with this.  
Hope this helps.  
Bharat

---

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 15, 2009, 12:50am UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/9 "2009-03-15T00:50:37Z")

</div>

In that case I won’t get any user object.  
Basically I am trying to implement in my application as mentioned here:  
[http://pivotallabs.com/users/nick/blog/articles/272-access-control-permissions-in-rails](http://pivotallabs.com/users/nick/blog/articles/272-access-control-permissions-in-rails)

For this I have some instance methods in User class. So the  
‘do\_somethin’ is basically not optional (only if user is logged in). So  
as suggested in the article, I am trying to create a null object.

I also looked at acts\_as\_nullobject plugin: [http://martincik.com/?p=22](http://martincik.com/?p=22) .  
But it is giving me some errors.

Any help/suggestions are welcome.

bill walton wrote:

> Hi Carlos,
> 
> On Sat, 2009-03-14 at 21:30 +0100, Carlos S. wrote:
> 
> > My objective is to avoid nil object errors when no user is logged in -  
> > i.e. when session[:user] is nil.
> > 
> > However, I still need to call some instance methods on this object.
> > 
> > Please suggest me how can I do this?
> 
> I’m thinkin’ I must be missin’ somethin’. Why can’t you use…
> 
> do\_somethin’ unless session[:user].nil?
> 
> ?
> 
> Best regards,  
> Bill

---

<div class="post-metadata">

**Author:** ![neubyr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/c37758/32.png) [@neubyr](https://www.ruby-forum.com/u/neubyr)\
**Post date:** [March 15, 2009, 4:43pm UTC](https://www.ruby-forum.com/t/null-object-pattern/162862/10 "2009-03-15T16:43:23Z")

</div>

I have a roles table and I check authorization as:

def can\_be\_deleted\_by?(user)  
return false if user.role.nil?  
valid\_roles = %w{admin creator}  
return false unless user.username == self.creuser ||  
valid\_roles.include?(user.role.name)  
return true  
end

One other thing I had to modify after using null obect was to check  
user.role.nil? before calling user.role.name, which otherwise checks for  
nil.name for anonymous user.

The delete action can be performed only by admin or the one who created  
that topic/item. Hence I am using roles as well as check by  
username(creator).

- 

CS.

Bharat R. wrote:

> Hello Carlos,  
> I am glad it worked for you. Access control is a fundamental  
> requirement along with authentication. Jim N.'s Bort which is  
> available on Github, packages Role Requirements written by Tim H.  
> along with Restful Authentication for creating a baseline  
> application. Tim has done an excellent job of implementing a  
> “minimal” authorization plugin. I am using Bort to develop my own  
> toolkit for creating applications.  
> I looked at the article that you list above. It is very well written  
> and very nice to learn from. The key thing missing from it is that it  
> fails to deal with Roles and instead deals directly with users. I  
> think a minimal layer of roles between users and controllers is a key  
> requirement.  
> I am not saying that Role Requirement is the only plugin that  
> addresses it. It is just that it packaged with Bort which has other  
> key plugins in addition to Restful Authentication and Role  
> Requirements. Gets the job done.  
> So instead of saying session[:current\_user].nil? you may want to say  
> [:current\_user].has\_role?(‘anonymous’) for example. See the method  
> “has\_role?” provided by Role Requirement? That is the key in my  
> opinion.  
> I may be wrong, but that is where I am going with this.  
> Hope this helps.  
> Bharat
