Module: Tins::DynamicScope
- Includes:
- Scope
- Defined in:
- lib/tins/dslkit.rb
Overview
A module that provides dynamic scope-based variable binding with hash contexts.
This module extends the basic Scope functionality to enable dynamic variable binding where variables can be set and accessed like methods, but stored in hash-based contexts. It's particularly useful for building DSLs, template engines, and context-sensitive applications.
Defined Under Namespace
Classes: Context
Instance Attribute Summary collapse
-
#dynamic_scope_name ⇒ Object
The name of the dynamic scope to use (defaults to :variables).
Instance Method Summary collapse
-
#dynamic_defined?(id) ⇒ Boolean
Checks if a variable is defined in any active dynamic scope.
-
#dynamic_scope {|void| ... } ⇒ Object
Creates a new dynamic scope context.
-
#method_missing(id, *args) ⇒ Object
Handles method calls that don't match existing methods.
Methods included from Scope
#scope, #scope_block, #scope_get, #scope_pop, #scope_push, #scope_reverse, #scope_top
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(id, *args) ⇒ Object
Handles method calls that don't match existing methods.
This implements the core dynamic variable binding behavior:
- For read operations (no arguments): Looks up the method name in active scopes and returns the value if found, otherwise delegates to super for normal method resolution
- For write operations (one argument + = suffix): Sets the value in current scope
- For all other cases: Delegates to super for normal method resolution
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 |
# File 'lib/tins/dslkit.rb', line 1162 def method_missing(id, *args) self.dynamic_scope_name ||= :variables if args.empty? and scope_reverse(dynamic_scope_name) { |c| c.key?(id) and return c[id] } super elsif args.size == 1 and id.to_s =~ /(.*?)=\Z/ c = scope_top(dynamic_scope_name) or super c[$1] = args.first else super end end |
Instance Attribute Details
#dynamic_scope_name ⇒ Object
The name of the dynamic scope to use (defaults to :variables).
1126 1127 1128 |
# File 'lib/tins/dslkit.rb', line 1126 def dynamic_scope_name @dynamic_scope_name end |
Instance Method Details
#dynamic_defined?(id) ⇒ Boolean
Checks if a variable is defined in any active dynamic scope.
1132 1133 1134 1135 1136 |
# File 'lib/tins/dslkit.rb', line 1132 def dynamic_defined?(id) self.dynamic_scope_name ||= :variables scope_reverse(dynamic_scope_name) { |c| c.key?(id) and return true } false end |
#dynamic_scope {|void| ... } ⇒ Object
Creates a new dynamic scope context.
This method pushes a new Context object onto the scope stack and yields to the provided block. When the block completes, the context is automatically popped from the stack.
1146 1147 1148 1149 |
# File 'lib/tins/dslkit.rb', line 1146 def dynamic_scope(&block) self.dynamic_scope_name ||= :variables scope_block(Context.new, dynamic_scope_name, &block) end |