Lua on Beans

MVC in Lua on Beans

Controllers

Controllers handle the logic of your application. They receive requests, interact with models, and prepare data for views.


-- app/controllers/users_controller.lua
local app = {
  index = function()
    Page("users/index", "app")
  end,

  new = index = function()
    Page("users/new", "app")
  end,

  edit = function()
    Page("users/edit", "app")
  end,

  create = function()
    -- do something
  end,

  update = function()
    -- do something
  end,

  delete = function()
    -- do something
  end,

  delete = function()
    Page("users/delete", "app")
  end,
}

Models

Models represent the data and business logic of your application. They interact with the database and define relationships between different data entities.

In Lua on Beans, models can interact with various databases. Here's an example using ArangoDB, but you could adapt this to work with other databases as well:


-- app/models/user.lua
return {
  all = function()
    return Adb.Aql([[
      FOR user IN users SORT user._key ASC RETURN user
    ]]).result
  end,

  get = function(key)
    return Adb.GetDocument("users/" .. key)
  end,

  create = function(dataset)
    return Adb.CreateDocument("users", dataset)
  end,

  update = function(key, dataset)
    return Adb.UpdateDocument("users/" .. key, dataset)
  end,

  destroy = function(key)
    return Adb.DeleteDocument("users/" .. key)
  end
}

Views

Views are responsible for presenting data to the user. In Lua on Beans, views are typically written using the etlua templating engine.


-- app/views/users/index.etlua
<h1>Users</h1>
<ul>
  <% for _, user in ipairs(users) do %>
    <li><%= user.name %> - <%= user.email %></li>
  <% end %>
</ul>
      

Partials

Partials are reusable view components that can be included in other views. They help in organizing and modularizing your view code.

To create a partial, add a new file in the app/views/partials directory. For example:


-- app/views/partials/_user_info.etlua
<div class="user-info">
  <h3><%= user.name %></h3>
  <p>Email: <%= user.email %></p>
  <p>Joined: <%= user.created_at %></p>
</div>

To use a partial in another view, use the Partial() function:


-- In any view file
<% for _, user in ipairs(users) do %>
  <%= Partial("user_info", { user = user }) %>
<% end %>

Partials are useful for:

  • Reusing common UI elements across multiple views
  • Breaking down complex views into smaller, manageable pieces
  • Improving code organization and maintainability