I am building a little test app with the Phoenix Framework. I cannot use Ecto since my DB is not supported. But I still want the MVC pattern. So I need a way to implement custom models. Since I'm coming from RoR I always catch myself thinking in Object Oriented Programming patterns where you have a class definition and instances with attributes that you can get and set. So that something like this is possible:
@mike = User.new
@mike.name = "Mike Power"
@mike.save
# ect
But this is clearly not how Elixir works.
I'm having a hard time wrapping my head around how to approach this. The implementation should allow me to:
- Have attributes
- Store values
- Manipulate values
- Validate values
- Save them to my database
The best way I have come up with so far is using structs. So something like this:
defmodule User do
defstruct name: "", age: 0
def sayhello do
IO.puts "Hi, I am #{name}"
# This is not working, I just put it here to make a point
end
end
tim = %User{}
# -> %User{age: 0, name: ""}
tim = %User{name: "Tim Turbo", age: 25}
# -> %User{age: 25, name: "Tim Turbo"}
tim.name
# -> "Tim Turbo"
# We can also change the values
tim = %User{name: "Michael"}
# -> %User{age: 25, name: "Michael"}
# It also makes sure that only the values defined in the struct can be set (which is nice)
tom = %User{unknown: "something"}
# ** (CompileError) iex:11: unknown key :unknown for struct User
Using vex I would even be able to implement validations quite easily
defmodule User do
defstruct username: nil, password: nil, password_confirmation: nil
use Vex.Struct
validates :username, presence: true,
length: [min: 4],
format: ~r/^[[:alpha:]][[:alnum:]]+$/
validates :password, length: [min: 4],
confirmation: true
end
So I am basically asking:
- Is this the way to go? Or is there a better one?
- And would I implement the function to actually save the user to the database also in my User module? Where I just enter the parameters
Something like this:
user = %User{params}
User.create user
ecto
's source is a good starting point: github.com/elixir-lang/ecto – sobolevn