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.