No commit activity in last 3 years
No release in over 3 years
The Schrodinger's Cat gem is a library that boasts neither novelty or ingenuity, just the potential for writing more efficient code when it comes to (and we've all been there) dealing with the ubiquitous cases wherein the existence (or nil'ness) of the object referenced is ever in flux. To this end, Schrodinger's Cat defines Object-level methods designed for theses common cases.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 1.0.0
>= 0
~> 1.8.4
~> 1.2.0
~> 3.12
~> 2.11.0
 Project Readme

Schrodinger’s Cat¶ ↑

Usage:¶ ↑

gem 'schrodingers-cat'
# or with GitHub for latest:
gem 'schrodinger', :git => "git://github.com/caleon/schrodinger.git"

Use case:¶ ↑

Able to avoid common patterns like:

user_or_id.is_a?(User) ? user_or_id.id : user_or_id

in favor of

user_or_id.if_a?(User).id # or
user_or_id.if_a?(User, :else => user_or_id).id
user_or_id.only_if_a?(User) || user_or_id

Note:¶ ↑

These can’t be overriden as they are not methods but low-level operators… ):

define_method(:"&&") {|obj| false }; define_method(:"||") {|obj| obj }

which means we can’t reliably do something like

record.assuming_a(User).authentications.first || raise "You didn't supply a user with authentications!"

because if sc.is_a?(SchrodingersCat), we ideally want:

sc || false     # => false
true && sc      # => false

but instead, as || and && are low-level operators for short-circuiting, we get:

sc || false     # => sc
true && sc      # => sc

However, though normally nil is the only object which should respond to #nil? with a true, so does SchrodingersCat whose MODEL_OBJECT is nil.

Examples:¶ ↑

Example 1:¶ ↑

if user_or_id.is_a?(User) then do #id, else just return user_or_id

    user_or_id = User.first
    user_or_id.if_a?(User).id
=>  1
    user_or_id = User.first.id
    user_or_id.if_a?(User).id
=>  1

Example 2:¶ ↑

Only if user_or_id.is_a?(User) run chained method normally. Otherwise, return nil on chained method call.

    possible_match = "hello".match(/ello/)
    possible_match.only_if_a?(MatchData)[0]
=>  "ello"
    possible_match = "hello".match(/superman/)
    possible_match.only_if_a?(MatchData)[0]
=>  nil

Example 3:¶ ↑

If user_or_id.is_a?(User) continue with chain, else continue returning Schrodinger’s Cat.

    user_or_id = User.first
  	res = user_or_id.assuming_a(User).authentications.first.provider # assuming an authentications record exists.
=>  "facebook"
  	res.class
=>  String
    user_or_id = User.find_by_email('nobody@juscribe.com') # if there is no user with that email,
  	res = user_or_id.assuming_a(User).authentications.first.provider
=>  nil
  	res.class
=>  SchrodingersCat

Additional information¶ ↑

Contributors¶ ↑

We have a short list of valued contributors. Check them all at:

github.com/caleon/schrodinger/contributors

Maintainers¶ ↑

License¶ ↑

MIT License. Copyright 2011-2012 caleon.