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
-
Enable the feature in a specific class via ‘include FeatureEnvy::ObjectLiteral` or …
-
Enable the feature in a specific scope via ‘using FeatureEnvy::ObjectLiteral`.
-
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:
“‘ruby 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`.
Class Method Summary collapse
Instance Method Summary collapse
-
#object { ... } ⇒ Object
Defines an object literal.
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.
69 70 71 |
# File 'lib/feature_envy/object_literal.rb', line 69 def object ... ObjectLiteral.object(...) end |