Skip to content

Instantly share code, notes, and snippets.

@ntl
Created June 15, 2018 21:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntl/0d519dd2a1cfa2b730794e81d57365c5 to your computer and use it in GitHub Desktop.
Save ntl/0d519dd2a1cfa2b730794e81d57365c5 to your computer and use it in GitHub Desktop.
Conditional Examples in Ruby
# 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 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)
# 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