The simplest gem you'll ever use

Afa6e65b91b46f3317c3d3e94e9255f2?s=47 Grzegorz Witek
February 25, 2016
14

The simplest gem you'll ever use

Afa6e65b91b46f3317c3d3e94e9255f2?s=128

Grzegorz Witek

February 25, 2016
Tweet

Transcript

  1. The simplest gem you’ll ever use @arnvald, 2016

  2. 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)
  3. 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!)
  4. 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
  5. 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]
  6. 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]>
  7. Let’s see the code

  8. 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
  9. Resources • http://trailblazer.to/gems/operation/ • https://github.com/arnvald/simple_operation

  10. We’re hiring! http://bit.do/kaligo-dev

  11. Questions?

  12. The simplest gem you’ll ever use @arnvald, 2016