Skip to content

Shortcuts and formatters

zverok edited this page Apr 13, 2016 · 6 revisions

There are several things that are not required by require "reality" (but are included in interactive console).

Pretty inspect

require "reality/pretty_inspect" redefines #inspect method for some Ruby core classes, which are heavily utilized by reality, and their default #inspect is not that pretty. For example:

# without pretty_inspect
Reality::Entity('Yukihiro Matsumoto').birthday
# => #<Date: 1965-04-14 ((2438865j,0s,0n),+0s,2299161j)>

# with pretty_inspect
Reality::Entity('Yukihiro Matsumoto').birthday
# => #<Date: 1965-04-14>

# without pretty_inspect
Reality::Entity('Buenos Aires').population / Reality::Entity('London').population
# => (2890151/8416535)
# ↑ it's Rational, pretty precise, but hard to read

# with pretty_inspect
Reality::Entity('Buenos Aires').population / Reality::Entity('London').population
# => 0.3
# ↑ it's still the same Rational, but with less precise/more readable output

Shortcuts

require "reality/shortcuts" provides you with pretty concise syntax:

include Reality

E('Yukihiro Matsumoto')

L('Argentine', 'Bolivia', 'Chile')

Include only methods

You could do include Reality::Methods (instead of include Reality) in your code to not pollute your namespace with anything except Entity and List methods (E and L is also in this namespace after you have required "reality/shortcuts").

Reality::Names module

This highly experimental module in current release allows you to work with reality entities as Ruby constants. It is not included by default even in interactive console.

It can be used like this:

# On itself:
Reality::Names::Argentina
# => #<Reality::Entity(Argentina):country>

# Or being included anywhere:
include Reality::Names

Argentina
# => #<Reality::Entity(Argentina):country>

BuenosAires # several words can be in CamelCase, or separated with _
# => #<Reality::Entity(Buenos Aires):city>

# Handy in complicated statements:
Argentina.capital.coord.distance_to(Iceland.capital)
# => #<Reality::Measure(11,447 km)>

ThisIsNonExisting # fallback to default behavior
# NameError: uninitialized constant Reality::Names::ThisIsNonExisting

Of course, redefining const_missing (which Reality::Names do) is a questionable practice, but it can help in two cases:

  • for creating data navigation environments and demos, with emphasizing "all data is Ruby object" approach;
  • for your own home scripting/experimenting, when you just want to type as less as possible :)