在Rails应用程序中实现链接列表堆栈

问题描述:

我想在我的Rails应用程序中实现链接列表堆栈,这是一个基本的待办事项列表。但我不确定我会在当前的Rails应用程序结构中放置链接列表的代码。有人可以提供任何指导吗?这是模型还是控制器?基本的在Rails应用程序中实现链接列表堆栈

截图待办事项应用 Todolist

任务控制器:

class TasksController < ApplicationController 

def create 
    @task = current_user.tasks.build(task_params) 

    if @task.save 
    flash[:notice] = "Task created successfully" 
    else 
    flash[:error] = "Error creating task" 
    end 

    redirect_to current_user 
end 

def destroy 
    @task = current_user.tasks.find(params[:id]) 

    if @task.destroy 
    flash[:notice] = "Task completed successfully" 
    else 
    flash[:error] = "Error completing task" 
    end 

    redirect_to current_user 
end 

private 

def task_params 
    params.require(:task).permit(:name) 
end 

Show.html.erb文件创建的任务

<h1>Hello, <%= current_user.email %></h1> 

<h2>Create New Task</h2> 
<%= form_for [current_user, @task] do |f| %> 
    <%= f.label :name %> 
    <%= f.text_field :name %> 
    <%= f.submit "Create", class: 'btn btn-primary' %> 
<% end %> 
<h2>Current Tasks</h2> 
<% current_user.tasks.each do | task| %> 
    <p> 
    <%= task.name %> 
    <%=link_to [current_user, task], method: :delete do %> 
     <span class="glyphicon glyphicon-ok"></span> 
    <% end %> 
    </p> 
<% end %> 

Task.rb(型号)

class Task < ActiveRecord::Base 
    belongs_to :user 
end 

User.rb(型号)

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    has_many :tasks 
    devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable 
end 

LinkedList的堆栈我想在Rails应用程序

module LinkedList 
    class Node 
    attr_accessor :value, :next_node 

    def initialize(value, next_node) 
     @value = value 
     @next_node = next_node 
     end 
    end 

    class Stack 
     def initialize 
     @first = nil 
     end 

     def push(value) 
     @first = Node.new(value, @first) 
     end 

     def pop 
     flash[:notice] = "Task completed successfully" if is_empty? 
     value = @first.value 
     @first = @first.next_node 
     value 
     end 

     def is_empty? 
     @first.nil? 
     end 
    end 

    end 
实施

任何非Web应用程序代码(即这可能是一个独立的Ruby对象)进入/lib文件夹。

首先在您的Rails应用程序中包含lib文件夹。

默认情况下不会这样做,因此人们可以在需要时灵活地明确地使用require-库的某些部分。

我们将通过执行以下操作,包括所有的lib

config.autoload_paths << Rails.root.join('lib') 

随后的lib里面,让我们创建一个linked_list.rb文件。

在这里你可以编写代码,它将被包含在你的应用程序中,由于自动加载每个第一级文件lib

对于更复杂的图书馆,我们称之为test,你需要做到以下几点:

  1. 做一个文件夹,名为test一个Ruby文件。
  2. 在该文件中,需要文件夹中的所有类。

例如:

# /lib/test/class1.rb 
module Test 
    class Class1 
    end 
end 

假设我们也有Class2Class3

# /lib/test.rb 
module Test 
end 

require 'test/class1' 
require 'test/class2' 
require 'test/class3'