Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The simplest gem you'll ever use

Grzegorz Witek
February 25, 2016
42

The simplest gem you'll ever use

Grzegorz Witek

February 25, 2016
Tweet

Transcript

  1. The simplest (shortest) gems • activesupport-json_encoder (~200 LOC) • rails-patch-json-encode

    (~35 LOC) • oj_mimic_json (10 LOC - without comments would fit into a tweet)
  2. So I wrote a gem • gem ‘simple_operation’ • version

    0.1.2 - 33 LOC • version 1.0.0 - 42 LOC (2 new features!) • ok, ok, it’s not the simplest gem ever (but close!)
  3. Services / Actions / Operations • operation class is a

    class that performs a set of steps • it has input (parameters) and output (result) • it has one public method • its name is a verb • it does not keep any state
  4. Example - validate records class SelectValidRecords < SimpleOperation.new(:records) def call

    records.select {|r| valid?(r) } end private def valid?(record); …; end end ValidateRecords.([invalid, invalid2, valid]) # => [valid]
  5. Example - validate records class ValidateRecords < SimpleOperation.new(:records) result :valid_records,

    :invalid_records def call split_records = records.group_by {|r| valid?(r)} result split_records[true], split_records[false] end private def valid?(record); …; end end ValidateRecords.([invalid, invalid2, valid]) # => <struct valid_records=[valid], invalid_records=[invalid,invalid2]>
  6. Ruby “tricks” used • overriding Class.new • using class_eval •

    using class name as a method name (in extension) • assigning class to a constant • using sugar syntax for call method