$30 off During Our Annual Pro Sale. View Details »

The simplest gem you'll ever use

Grzegorz Witek
February 25, 2016
25

The simplest gem you'll ever use

Grzegorz Witek

February 25, 2016
Tweet

Transcript

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

    View Slide

  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)

    View Slide

  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!)

    View Slide

  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

    View Slide

  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]

    View Slide

  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])
    # => invalid_records=[invalid,invalid2]>

    View Slide

  7. Let’s see the code

    View Slide

  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

    View Slide

  9. Resources
    • http://trailblazer.to/gems/operation/
    • https://github.com/arnvald/simple_operation

    View Slide

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

    View Slide

  11. Questions?

    View Slide

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

    View Slide