Skip to content

Commit 211fb55

Browse files
author
Tim Rogers
committed
Document how to check whether Spring is running from within your code
You can check whether Spring is running by checking whether the `Spring` constant is defined. ```ruby if defined?(Spring) # This code will only run if Spring is running. end ``` This is the approach taken by Spring binary, [`bin/spring`][1]. I've often personally wanted to check whether Spring is running (e.g. when I've been seeing strange behaviour that I suspect is related to class reloading), and this is potentially useful for other gems too (e.g. to warn if environment variables might not be reflected as expected due to running through the Spring preloader). [1]: https://github.com/rails/spring/blob/master/bin/spring#L3
1 parent 156dcbf commit 211fb55

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,24 @@ $ bin/spring stop
176176
Spring stopped.
177177
```
178178

179+
From within your code, you can check whether Spring is active by checking whether the
180+
`Spring` constant is defined:
181+
182+
```ruby
183+
# With Spring running
184+
defined?(Spring)
185+
# => "constant"
186+
187+
# With Spring disabled
188+
defined?(Spring)
189+
# => nil
190+
191+
# Since a string is truthy and `nil` is falsy, we can use this as our condition
192+
if defined?(Spring)
193+
# Do something
194+
end
195+
```
196+
179197
### Removal
180198

181199
To remove spring:

0 commit comments

Comments
 (0)