zoukankan      html  css  js  c++  java
  • [sinatra] Just Do It: Learn Sinatra, Part One Darren Jones

    1. Install sinatra gem

    gem install sinatra --no-ri --no-rdoc
    

    2. Basic App

    #!/usr/bin/ruby
    require 'sinatra'
    get '/' do
    	"Just Do It"
    end
    

    ruby低于1.9,需要在文件开头加require 'rubygems'

    ruby basic.rb
    

    Open up your browser and go to http://localhost:4567.

    3. Inline Template

    Slim is a fantastic template engine that makes this a much easier task.

    Install slime: $ gem install slime

    #!/usr/bin/ruby
    require "sinatra"
    require 'slim'
    
    get '/' do
    	slim:index
    end
    
    #Inline templates always come after the __END__ declaration, and each template begins with @@.
    
    __END__
    
    @@layout
    doctype html
    html
    	head
    		meta charset="utf-8"
    		title Just Do it
    		link rel="stylesheet" media="screen,projection" href="/style.css"
    		/[if lt IE 9]
    			script scr="http://html5shiv.googlecode.com/svn/trunk/html5.js"
    	body
    		h1 Just Doi it
    		== yield 
    
    
    @@index 
    h2 My tasks
    ul.tasks
    	li Get Milk		
    

    "@@layout" template: This will automatically be rendered with every view and provides a basic HTML5 scaffolding. The key line in the layout template is right at the end (==yield). The yield statement renders the content from the whichever template was requested by the handler (in this case, ‘index’).

    4. Extend Views (把视图分离出来)

    5. Dynamic Content

     在主文件rb中增加代码

    get "/:task" do
    	@task=params[:task].split('-').join(' ').capitalize
    	slim :task
    end
    

    ‘@task’ equal to the value of params[:task]

    对应的视图文件task.slim

    h2 My Tasks
    = @task
    

    其中@task匹配对应的URL。

    6.Forms(窗体处理)

     本例把index.slim的内容替换成

    form action="/" method="POST"
      input type="text" name="task"
      input.button type="submit" value="New Task >>"
    

    这样会在“/”页面显示一个窗体(一个文本框、一个提交按钮)

    提交的内容需要一个handler来处理,再sinatra文件中用post(对应窗体提交method),代码如下:

    post '/' do
      @task =  params[:task]
      slim :task
    end
    
  • 相关阅读:
    SQL复制表
    文件流 修改二进制文件
    C#代码开启或关闭window service
    程序员之间的相处
    .NET实现图片下载(后台)
    当要存入数据的数据为null时 必须转换成DBNull.Value
    Maven第三篇【Maven术语、pom.xml介绍】
    Maven第二篇【Idea下使用Maven】
    Maven第一篇【介绍、安装、结构目录】
    SSM整合开发
  • 原文地址:https://www.cnblogs.com/lizunicon/p/3600814.html
Copyright © 2011-2022 走看看