Module: Shamu::Entities::NullEntity

Defined in:
lib/shamu/entities/null_entity.rb

Overview

Null entities look at feel just like their natural counterparts but are not backed by any real data. Rather than returning null from a service lookup function, services will return a null entity so that clients do not need to constantly check for nil before formatting output.

class UserEntity < Entity
  attribute :name
  attribute :id
  attribute :email
end

class NullUserEntity < UserEntity
  include NullEntity
end

user = user_service.lookup( real_user_id )
user       # => UserEntity
user.name  # => "Shamu"
user.email # => "[email protected]"
user.id    # => 5

user = user_service.lookup( unknown_user_id )
user       # => NullUserEntity
user.name  # => "Unknown User"
user.email # => nil
user.id    # => nil

Constant Summary collapse

AUTO_FORMATTED_ATTRIBUTES =

Attributes to automatically format as "Unknown Class Name"

%i( name title label ).freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.for(entity_class) ⇒ Class

Dynamically generate a new null entity class.

Parameters:

  • entity_class (Class)

    Entity class

Returns:

  • (Class)

    a null entity class derived from entity_class.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/shamu/entities/null_entity.rb', line 73

def self.for( entity_class )
  if null_klass = ( entity_class.const_defined?( :NullEntity, false ) &&
                    entity_class.const_get( :NullEntity, false ) )
    # If the base class is reloaded a-la rails dev, then regenerate the
    # null class as well.
    null_klass = nil if null_klass.superclass != entity_class
  end

  unless null_klass
    null_klass = Class.new( entity_class )
    entity_class.const_set :NullEntity, null_klass

    # After const_set so we have name and inheritance
    null_klass.include ::Shamu::Entities::NullEntity
  end

  null_klass
end

Instance Method Details

#empty?true

Allow clients to adjust behavior if needed for missing entities.

Returns:

  • (true)


45
46
47
# File 'lib/shamu/entities/null_entity.rb', line 45

def empty?
  true
end

#to_paramnil

Prevent rails url helpers from generating URLs for the entity.

Returns:

  • (nil)


39
40
# File 'lib/shamu/entities/null_entity.rb', line 39

def to_param
end