Reputation: 83
I have this model:
defmodule MyApp.MyModel do
use MyApp.Web, :model
import Ecto.Query
# ....
How can I add an instance method to it which also uses other field on MyModel? This doesn't work because on an html page it throws an exception saying the key :my_method not found
defmodule MyApp.MyModel do
use MyApp.Web, :model
import Ecto.Query
# doesn't work
def my_method do
# how can I get access to "this" or "self" from here?
"test"
end
Upvotes: 2
Views: 1654
Reputation: 84150
Since Elixir is a functional programming language, you don't have methods, you have functions. You also don't have the concept of "instances". There is a self function, which is used to identify the PID for the current process, however it shouldn't be confused with "this" which you may be used to in other programming languages.
Functions are always invoked with:
module.function(arg1, arg2)
So to call the my_method
function in your example (which I have renamed my_func
), you would do:
def my_func(my_model) do
my_model.some_attribute
end
The thing to notice here is that you must pass the struct as an argument to the function. You would then call this with:
foo = %MyModel{}
MyModel.my_func(foo)
http://elixir-lang.org/getting-started/introduction.html is a great way to learn about the way functions in Elixir work.
Upvotes: 11