Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Message Validation

exercises/message_validation.livemd

Message Validation

Mix.install([
  {:jason, "~> 1.4"},
  {:kino, "~> 0.9", override: true},
  {:youtube, github: "brooklinjazz/youtube"},
  {:hidden_cell, github: "brooklinjazz/hidden_cell"}
])

Navigation

Home Report An Issue WithUser Validation

Message Validation

You’re going to use guards to create a Message module that only allows messages in the form of a string or a Message struct with a :body field to be sent. Sending a message simply returns a string of the message prepended with "Sent: ".

Message.send("hello!")
"Sent: hello!"

Message.send(%Message{body: "hi!"})
"Sent: hi!"

Invalid messages should raise a FunctionClauseError.

Message.send(123)
** (FunctionClauseError) no function clause matching in Message.send/1    
    
    The following arguments were given to Message.send/1:
    
        # 1
        123

Example Solution

defmodule Message do
  defstruct [:body]
  def send(message) when is_binary(message) do
    "Sent: " <> message
  end

  def send(message) when is_binary(message.body) do
    "Sent: " <> message.body
  end
end

Implement the Message module as documented below.

defmodule Message do
  @moduledoc """
  Send messages between users.
  Returns a string of the message if provided valid input.

  ## Examples

    iex> Message.send("hello!")
    "Sent: hello!"

    iex> Message.send(%Message{body: "hi!"})
    "Sent: hi!"

    iex> Message.send(123)
    ** (FunctionClauseError) no function clause matching in Message.send/1
  """
  defstruct [:body]
end

Commit Your Progress

DockYard Academy now recommends you use the latest Release rather than forking or cloning our repository.

Run git status to ensure there are no undesirable changes. Then run the following in your command line from the curriculum folder to commit your progress.

$ git add .
$ git commit -m "finish Message Validation exercise"
$ git push

We’re proud to offer our open-source curriculum free of charge for anyone to learn from at their own pace.

We also offer a paid course where you can learn from an instructor alongside a cohort of your peers. We will accept applications for the June-August 2023 cohort soon.

Navigation

Home Report An Issue WithUser Validation