Module: FeatureEnvy::ObjectLiteral

Defined in:
lib/feature_envy/object_literal.rb

Overview

Object literals.

Definition

An expression that results in creating of an object with a predefined set of attributes and methods, without having to define and instantiated a class.

Applications

Defining singleton objects, both state and methods, without having to define their class explicitly.

Usage

  1. Enable the feature in a specific class via include FeatureEnvy::ObjectLiteral or ...
  2. Enable the feature in a specific scope via using FeatureEnvy::ObjectLiteral.
  3. Create objects by calling object { ... }.

Discussion

Ruby does not offer literals for defining arbitrary objects. Fortunately, that gap is easy to fill with a helper method. The snippet below is literally how Feature Envy implements object literals:

def object &definition
  object = Object.new
  object.instance_eval &definition
  object
end

All attributes set and methods defined inside the block will be set on object.

Examples:

# Enable the feature in the current scope.
using FeatureEnvy::ObjectLiteral

# Assuming `database` and `router` are already defined.
app = object do
  @database = database
  @router   = router

  def start
    @database.connect
    @router.activate
  end
end

app.start

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.object(&definition) ⇒ Object



74
75
76
77
78
# File 'lib/feature_envy/object_literal.rb', line 74

def self.object &definition
  result = Object.new
  result.instance_eval &definition
  result
end

Instance Method Details

#object { ... } ⇒ Object

Defines an object literal.

Yields:

  • The block is evaluated in the context of a newly created object. Instance attributes and methods can be defined within the block and will end up being set on the resulting object.

Returns:

  • (Object)

    The object defined by the block passed to the call.



69
70
71
# File 'lib/feature_envy/object_literal.rb', line 69

def object ...
  ObjectLiteral.object(...)
end