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

Typed Ruby

Typed Ruby

Ruby has is a dynamic language, it has no types, why would we care?

Nikita Shilnikov

October 21, 2017
Tweet

More Decks by Nikita Shilnikov

Other Decks in Programming

Transcript

  1. View Slide

  2. Nikita Shilnikov
    Me

    View Slide

  3. I work on

    View Slide

  4. Typed Ruby

    View Slide

  5. There are no types
    in Ruby

    View Slide

  6. Everything is an object

    View Slide

  7. Objects interact via
    message passing

    View Slide

  8. 1 + 2

    View Slide

  9. 1
    :+,2
    message target

    View Slide

  10. 1.methods

    View Slide

  11. => [:%, :&, :*, :+, :-, :/, :, :^, :|, :~, :[email protected], :**, :<=>, :<:>>, :<=, :>=, :==, :===, :[], :inspect, :size, :succ, :to_int, :to_s,
    :to_i, :to_f, :next, :div, :upto, :chr, :ord, :coerce, :divmod, :fdiv,
    :modulo, :remainder, :abs, :magnitude, :integer?, :floor, :ceil,
    :round, :truncate, :odd?, :even?, :downto, :times, :pred, :bit_length,
    :digits, :to_r, :numerator, :denominator, :rationalize, :gcd, :lcm,
    :gcdlcm, :[email protected], :eql?, :singleton_method_added, :i, :real?, :zero?,
    :nonzero?, :finite?, :infinite?, :step, :positive?, :negative?, :quo,
    :arg, :rectangular, :rect, :polar, :real, :imaginary, :imag, :abs2,
    :angle, :phase, :conjugate, :conj, :to_c, :between?, :clamp,
    :instance_of?, :kind_of?, :is_a?, :tap, :public_send,
    :remove_instance_variable, :public_method, :singleton_method,
    :instance_variable_set, :define_singleton_method, :method, :extend,
    :to_enum, :enum_for, :=~, :!~, :respond_to?, :freeze, :object_id,
    :send, :display, :nil?, :hash, :class, :singleton_class, :clone, :dup,
    :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust,
    :frozen?, :methods, :singleton_methods, :protected_methods,
    :private_methods, :public_methods, :instance_variable_get,
    :instance_variables, :instance_variable_defined?, :!, :!=,
    :__send__, :equal?, :instance_eval, :instance_exec, :__id__]

    View Slide

  12. => [:%, :&, :*, :+, :-, :/, :, :^, :|, :~, :[email protected], :**, :<=>, :<:>>, :<=, :>=, :==, :===, :[], :inspect, :size, :succ, :to_int, :to_s,
    :to_i, :to_f, :next, :div, :upto, :chr, :ord, :coerce, :divmod, :fdiv,
    :modulo, :remainder, :abs, :magnitude, :integer?, :floor, :ceil,
    :round, :truncate, :odd?, :even?, :downto, :times, :pred, :bit_length,
    :digits, :to_r, :numerator, :denominator, :rationalize, :gcd, :lcm,
    :gcdlcm, :[email protected], :eql?, :singleton_method_added, :i, :real?, :zero?,
    :nonzero?, :finite?, :infinite?, :step, :positive?, :negative?, :quo,
    :arg, :rectangular, :rect, :polar, :real, :imaginary, :imag, :abs2,
    :angle, :phase, :conjugate, :conj, :to_c, :between?, :clamp,
    :instance_of?, :kind_of?, :is_a?, :tap, :public_send,
    :remove_instance_variable, :public_method, :singleton_method,
    :instance_variable_set, :define_singleton_method, :method, :extend,
    :to_enum, :enum_for, :=~, :!~, :respond_to?, :freeze, :object_id,
    :send, :display, :nil?, :hash, :class, :singleton_class, :clone, :dup,
    :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust,
    :frozen?, :methods, :singleton_methods, :protected_methods,
    :private_methods, :public_methods, :instance_variable_get,
    :instance_variables, :instance_variable_defined?, :!, :!=,
    :__send__, :equal?, :instance_eval, :instance_exec, :__id__]

    View Slide

  13. Duck typing

    View Slide

  14. a + b

    View Slide

  15. a.respond_to?(:+)

    View Slide

  16. Consequences

    View Slide

  17. foo.size # => 8

    View Slide

  18. foo.size # => 8

    View Slide

  19. A real world example

    View Slide

  20. name = params[:name]

    View Slide

  21. name = params[:name]
    String

    View Slide

  22. name # => true

    View Slide

  23. name # => true







    View Slide

  24. But true is not a String!

    View Slide

  25. name.camelize

    View Slide

  26. new_user = User.new(params.permit(:name))
    new_user.name # => ?

    View Slide

  27. "t"

    View Slide

  28. View Slide

  29. View Slide

  30. Problems
    1. Using models for coercion is questionable.

    2. Coercion logic is opaque.

    3. Types are defined by database columns.

    4. Unhappy paths end with an error (better) or a
    data corruption (worse).

    View Slide

  31. Duck typing is unreliable
    when working with data

    View Slide

  32. Duck typing is unreliable
    when working with data

    View Slide

  33. Duck typing is unreliable
    when working with data

    View Slide

  34. What is a type?

    View Slide

  35. What is a type?
    1. A category of people or things having common
    characteristics.

    2. A person or thing exemplifying the ideal or
    defining characteristics of something
    (prototype).

    3. Characters or letters that are printed or shown
    on a screen.

    View Slide

  36. What is a type?
    1. A category of people or things having common
    characteristics.

    2. A person or thing exemplifying the ideal or
    defining characteristics of something
    (prototype).

    3. Characters or letters that are printed or shown
    on a screen.

    View Slide

  37. A category of people or things having
    common characteristics
    1. Natural numbers (1, 2, 3, 4, ...).

    2. Emojis ( ...).

    3. Vertebrates (dog, cat, horse, ...).

    View Slide

  38. Types in programming
    Also called data types.
    Play a major role in statically typed
    languages.

    View Slide

  39. Types in static
    languages

    View Slide

  40. –Haskell Wiki
    “Types are how you
    describe the data your
    program will work with.”

    View Slide

  41. –Type-Driven Development with Idris
    “Types are a means of
    classifying (data) values.”

    View Slide

  42. data Planet = Earth

    View Slide

  43. data Planet = Earth
    keyword

    View Slide

  44. data Planet = Earth
    type name

    View Slide

  45. data Planet = Earth
    value

    View Slide

  46. data Planet = Earth | Mars | ...
    values

    View Slide

  47. isEarth Earth = True
    isEarth x = False

    View Slide

  48. isEarth Earth = True
    isEarth x = False

    View Slide

  49. def earth?(planet)
    planet == :earth
    end

    View Slide

  50. def earth?(planet)
    planet.public_send(:==, :earth)
    end

    View Slide

  51. earth?(:earth) # => true
    earth?(:mars) # => false
    earth?(:sun) # => false
    earth?(1) # => false

    View Slide

  52. isEarth 1

    View Slide

  53. isEarth :: Planet -> Bool

    View Slide

  54. isEarth :: Planet -> Bool

    View Slide

  55. 1. Early sanity-check, the compiler will check
    your code for consistency.

    2. Advanced compilers can check a program for
    correctness.

    3. Better semantics and docs.

    4. Better introspection/IDE integration.

    5. A lot of performance optimizations can be
    done during the compile phase.
    Pros:

    View Slide

  56. 1. Compilation takes time.

    2. Types require more typing making code more
    verbose and less flexible.
    Cons:

    View Slide

  57. Statically typed
    languages have
    type inference

    View Slide

  58. val firstName = "Adam"

    View Slide

  59. Dynamically typed
    languages have
    type annotations

    View Slide

  60. def is_earth(planet: Planet):
    ...

    View Slide

  61. Types in Ruby

    View Slide

  62. Duck typing has
    nothing to do with
    types

    View Slide

  63. Duck typing is
    useless for
    describing data

    View Slide

  64. Applications are
    useless without
    data

    View Slide

  65. View Slide

  66. dry-validation

    View Slide

  67. schema
    raw input valid data
    app DB
    errors

    View Slide

  68. outer world
    application

    View Slide

  69. CreateUserSchema = Dry::Validation.JSON do
    required(:name).filled(:str?)
    end

    View Slide

  70. CreateUserSchema.call(params)

    View Slide

  71. CreateUserSchema.call('name' => 'John').output
    # => { name: 'John' }

    View Slide

  72. CreateUserSchema.call('name' => true).output
    # => { name: ["must be a string"] }

    View Slide

  73. View Slide

  74. something.blank?

    View Slide

  75. dry-types

    View Slide

  76. —a type system built for coercion and data
    validation;

    —formerly known as dry-data;

    —initially was created as a replacement for
    virtus;

    —is a direct dependency of dry-validation,
    ROM, and hanami-model.
    dry-types

    View Slide

  77. Adding types to
    Ruby

    View Slide

  78. View Slide

  79. module Types
    include Dry::Types.module
    end

    View Slide

  80. int = Types::Strict::Int
    int[3] # => 3

    View Slide

  81. int = Types::Strict::Int
    int[3] # => 3
    int['3']
    # => '3' violates constraints
    # (type?(Integer, '3') failed)

    View Slide

  82. int = Types::Coercible::Int
    int[3] # => 3
    int['3'] # => 3

    View Slide

  83. Integer('3')
    nil.to_i # => 0
    Integer(nil) # => TypeError
    ''.to_i # => 0
    Integer('') # => ArgumentError

    View Slide

  84. Type constraints

    View Slide

  85. View Slide

  86. Types are like sets

    View Slide

  87. View Slide

  88. Types::Age = Types::Strict::Int.constrained(gteq: 18)

    View Slide

  89. Case equality

    View Slide

  90. case value
    when Types::Strict::Int then :number
    when Types::Strict::String then :str
    end

    View Slide

  91. Types have algebra*

    View Slide

  92. Types::Strict::Int | Types::Strict::String

    View Slide

  93. dry-struct

    View Slide

  94. class User < Dry::Struct
    attribute :name, Types::Strict::String
    attribute :age, Types::Age
    end

    View Slide

  95. Structs are meant to
    be valid

    View Slide

  96. module ProfileEvents
    class PasswordChanged < Dry::Struct
    attribute :user_id, Types::UUID
    attribute :password, Types::Password
    end
    class EmailChanged < Dry::Struct
    attribute :user_id, Types::UUID
    attribute :email, Types::Email
    end
    Updated = PasswordChanged | EmailChanged
    end

    View Slide

  97. module ProfileEvents
    class PasswordChanged < Dry::Struct
    attribute :user_id, Types::UUID
    attribute :password, Types::Password
    end
    class EmailChanged < Dry::Struct
    attribute :user_id, Types::UUID
    attribute :email, Types::Email
    end
    Updated = PasswordChanged | EmailChanged
    end

    View Slide

  98. module ProfileEvents
    class PasswordChanged < Dry::Struct
    attribute :user_id, Types::UUID
    attribute :password, Types::Password
    end
    class EmailChanged < Dry::Struct
    attribute :user_id, Types::UUID
    attribute :email, Types::Email
    end
    Updated = PasswordChanged | EmailChanged
    end

    View Slide

  99. Custom types

    View Slide

  100. module Types
    include Dry::Types.module
    end
    Types.Instance(Customer)
    Types.Constructor(Geopoint) { |lon, lat|
    "POINT (#{ lat } #{ lon })"
    }
    Types.Constant(:only_allowed)

    View Slide

  101. What’s inside?

    View Slide

  102. Types are values

    View Slide

  103. Types::Int.constrained(gteq: 18) == Types::Int.constrained(gteq: 18)

    View Slide

  104. age = Types::Strict::Int.constrained(gteq: 18)
    types = {
    age => :age
    }
    types[Types::Strict::Int.constrained(gteq: 18)] # => :age

    View Slide

  105. schema do
    attribute :company, Types::String
    attribute :license, Types::PG::JSONB
    end

    View Slide

  106. where { license.contain(enabled: true) }
    # WHERE "companies"."license" @> '{"enabled":true}'::jsonb)

    View Slide

  107. TypeExtensions.register(JSONB) do
    def contain(type, expr, value)
    sql = wrap(expr).contains(value)
    Attribute[SQL::Types::Bool].meta(sql_expr: sql)
    end
    end

    View Slide

  108. ROM 4.0 is out

    View Slide

  109. Types have metadata

    View Slide

  110. first_name = Types::Strict::String.
    constrained(min_size: 3)
    last_name = Types::Strict::String.
    constrained(min_size: 3)

    View Slide

  111. first_name = Types::Strict::String.
    constrained(min_size: 3).
    meta(name: 'first_name')
    last_name = Types::Strict::String.
    constrained(min_size: 3).
    meta(name: 'last_name')

    View Slide

  112. Types have ASTs

    View Slide

  113. Types::Strict::String.constrained(min_size: 3)
    # => #primitive=String options={} meta={}>
    options={:rule=>#rules=[#Module(Dry::Logic::Predicates::Methods)#type?>
    options={:args=>[String]}>, #predicate=#Module(Dry::Logic::Predicates::Methods)#min_size?>
    options={:args=>[3]}>] options={}>}
    rule=#rules=[#Module(Dry::Logic::Predicates::Methods)#type?>
    options={:args=>[String]}>, #predicate=#Module(Dry::Logic::Predicates::Methods)#min_size?>
    options={:args=>[3]}>] options={}> meta={}>

    View Slide

  114. int = Types::Strict::Int
    int.to_ast
    [:constrained,
    [[:definition, [Integer, {}]],
    [:predicate,
    [:type?,
    [[:type, Integer],
    [:input, Undefined]]]], {}]]

    View Slide

  115. require 'dry/types/compiler'
    compiler = Dry::Types::Compiler.new(Dry::Types)
    int = Types::Strict::Int
    int == compiler.(int.to_ast)

    View Slide

  116. Age (Int >= 18) rand(50) + 18

    View Slide

  117. —data generators;

    —serializers;

    —data transformers;

    —auto-docs;

    —???

    View Slide

  118. Types make life easier

    View Slide

  119. Types make life easier
    So use them

    View Slide

  120. Recap
    — Duck typing is neither about ducks nor typing.

    — Types are sets of possible values that shape
    the data.

    — In dry-types types are ordinary objects that
    can be build and composed.

    — Types can even be decomposed allowing you
    to build new abstractions on top of them.

    View Slide

  121. Do not use .blank?

    View Slide

  122. It’s not about Haskell

    View Slide

  123. 1.0 is almost there

    View Slide

  124. Links
    dry-rb.org/gems/dry-types

    github.com/dry-rb/dry-types

    discourse.dry-rb.org

    gitter.im/dry-rb/chat

    View Slide

  125. Thank you!
    github.com/flash-gordon

    @NikitaShilnikov

    View Slide