Created
June 15, 2018 21:02
-
-
Save ntl/0d519dd2a1cfa2b730794e81d57365c5 to your computer and use it in GitHub Desktop.
Conditional Examples in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is an example using Eventide's message handling DSL for declaring different | |
# handler methods based on message type | |
class SomeHandler | |
include Messaging::Handle | |
handle SomeMessage do |some_msg| | |
# ... | |
end | |
handle OtherMessage do |other_msg| | |
# ... | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a pattern @sbellware taught me (and possibly invented). When a method call | |
# can have ancillary return values, the method can then accept an `include' keyword | |
# argument (optionally) that specifies additional return values. For intsance, given | |
# a store that fetches entities, and *also* caches them behind the scenes, we can | |
# tell a store to fetch an entity *and* return the timestamp for when the entity | |
# was cached. | |
# Normal fetch call, only returns an entity | |
entity = store.fetch(id) | |
# Include the cache record timestamp in the return value | |
entity, cached_time = store.fetch(id, include: :cached_time) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Traditional, perform a query, make a decision based on the result. | |
# Note that in practice, the query *and* the decision should always go | |
# in the same class. The danger with result objects is that they allow | |
# query results to break encapsulation | |
class SomeClass | |
def initializer(id) | |
@id = id | |
end | |
def some_method | |
entity = SomeRepository.get(@id) | |
if entity.nil? | |
# ... | |
else | |
# ... | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment