`
biyeah
  • 浏览: 202886 次
  • 来自: ...
社区版块
存档分类
最新评论

camping 一个小巧的ruby web framework

    博客分类:
  • Ruby
 
阅读更多
https://github.com/camping/camping/blob/master/book/02_getting_started
直接看文档就知道了。
源代码不大4k左右值得研究。
Camping is a web framework which consistently stays at less than 4kB of code.You can probably view the complete source code on a single page.
= Getting Started

Start a new text file called nuts.rb. Here's what you put inside:

  Camping.goes :Nuts

Save it. Then, open a command prompt in the same directory. You'll want to
run:

  $ camping nuts.rb

And you should get a message which reads:

  ** Camping running on 0.0.0.0:3301.

This means that right now The Camping Server is running on port 3301 on your
machine. Open your browser and visit http://localhost:3301/.

Your browser window should show:

  Camping Problem!
 
  / Not found

No problem with that. The Camping Server is running, but it doesn't know what
to show. Let's tell him.

== Hello clock

So, you've got Camping installed and it's running. Keep it running. You can
edit files and The Camping Server will reload automatically. When you need to
stop the server, press Control-C.

Let's show something. At the bottom of nuts.rb add:

  module Nuts::Controllers
    class Index < R '/'
      def get
        Time.now.to_s
      end
    end
  end

Save the file and refresh the browser window. Your browser window should show
the time, e.g.

  Sun Jul 15 12:56:15 +0200 2007

== Enjoying the view

The Camping microframework allows us to separate our code using the MVC
(Model-View-Controller) design pattern. Let's add a view to our Nuts
application. Replace the <tt>module Nuts::Controllers</tt> with:

  module Nuts::Controllers
    class Index < R '/'
      def get
        @time = Time.now
        render :sundial
      end
    end
  end

  module Nuts::Views
    def layout
      html do
        head do
          title { "Nuts And GORP" }
        end
        body { self << yield }
      end
    end

    def sundial
      p "The current time is: #{@time}"
    end
  end
 
Save the file and refresh your browser window and it should show a message
like:

   The current time is: Sun Jul 15 13:05:41 +0200 2007

And the window title reads "Nuts And GORP".

Here you can see we call <tt>render :sundial</tt> from our controller. This
does exactly what it says, and renders our <tt>sundial</tt> method. We've also
added a special method called <tt>layout</tt> which Camping will automatically
wrap our sundial output in. If you're familiar with HTML, you'll see that our
view contains what looks HTML tag names. This is Markaby, which is like
writing HTML using Ruby!

Soon enough, you'll find that you can return anything from the controller, and
it will be sent to the browser. But let's keep that for later and start
investigating the routes.

== Routes

You probably noticed the weird <tt>R '/'</tt> syntax in the previous page.
This is an uncommon feature of Ruby that is used in our favorite
microframework, to describe the routes which the controller can be accessed
on.

These routes can be very powerful, but we're going to have look at the
simplest ones first.

  module Nuts::Controllers
    class Words < R '/welcome/to/my/site'
      def get
        "You got here by: /welcome/to/my/site"
      end
    end
   
    class Digits < R '/nuts/(\d+)'
      def get(number)
        "You got here by: /nuts/#{number}"
      end
    end

    class Segment < R '/gorp/([^/]+)'
      def get(everything_else_than_a_slash)
        "You got here by: /gorp/#{everything_else_than_a_slash}"
      end
    end
   
    class DigitsAndEverything < R '/nuts/(\d+)/([^/]+)'
      def get(number, everything)
        "You got here by: /nuts/#{number}/#{everything}"
      end
    end
  end
 
Add this to nuts.rb and try if you can hit all of the controllers.

Also notice how everything inside a parenthesis gets passed into the method,
and is ready at your disposal.

=== Simpler routes

This just in:

  module Nuts::Controllers
    class Index
      def get
        "You got here by: /"
      end
    end
   
    class WelcomeToMySite
      def get
        "You got here by: /welcome/to/my/site"
      end
    end
   
    class NutsN
      def get(number)
        "You got here by: /nuts/#{number}"
      end
    end
   
    class GorpX
      def get(everything_else_than_a_slash)
        "You got here by: /gorp/#{everything_else_than_a_slash}"
      end
    end
   
    class NutsNX
      def get(number, everything)
        "You got here by: /nuts/#{number}/#{everything}"
      end
    end
  end
 
Drop the <tt>< R</tt>-part and it attemps to read your mind. It won't always
succeed, but it can simplify your application once in a while.

== Modeling the world

You can get pretty far with what you've learned now, and hopefully you've been
playing a bit off-book, but it's time to take the next step: Storing data.

Let's start over again.

  Camping.goes :Nuts

  module Nuts::Models
    class Page < Base
    end
  end
 
Obviously, this won't do anything, since we don't have any controllers, but
let's rather have a look at we _do_ have.

We have a model named Page. This means we now can store wiki pages and
retrieve them later. In fact, we can have as many models as we want. Need one
for your users and one for your blog posts? Well, I think you already know how
to do it.

However, our model is missing something essential: a skeleton.
 
  Camping.goes :Nuts
 
  module Nuts::Models
    class Page < Base
    end
 
    class BasicFields < V 1.0
      def self.up
        create_table Page.table_name do |t|
          t.string :title
          t.text   :content
          # This gives us created_at and updated_at
          t.timestamps
        end
      end
 
      def self.down
        drop_table Page.table_name
      end
    end
  end
 
Now we have our first version of our model. It says:

  If you want to migrate up to version one,
    create the skeleton for the Page model,
    which should be able to store,
      "title" which is a string,
      "content" which is a larger text,
      "created_at" which is the time it was created,
      "updated_at" which is the previous time it was updated.
   
  If you want to migrate down from version one,
    remove the skeleton for the Page model.
   
This is called a _migration_. Whenever you want to change or add new models you simply add a new migration below, where you increase the version number. All of these migrations builds upon each other like LEGO blocks.

Now we just need to tell Camping to use our migration. Write this at the bottom of nuts.rb

  def Nuts.create
    Nuts::Models.create_schema
  end

When The Camping Server boots up, it will automatically call
<tt>Nuts.create</tt>. You can put all kind of startup-code here, but right now
we only want to create our skeleton (or upgrade if needed). Start The Camping
Server again and observe:
 
  $ camping nuts.rb
  ** Starting Mongrel on 0.0.0.0:3301
  -- create_table("nuts_schema_infos")
     -> 0.1035s
  ==  Nuts::Models::BasicFields: migrating ===================================
  -- create_table(:nuts_pages)
     -> 0.0033s
  ==  Nuts::Models::BasicFields: migrated (0.0038s) ==========================
 
Restart it, and enjoy the silence. There's no point of re-creating the
skeleton this time.

Before we go on, there's one rule you must known: Always place your models
before your migrations.

== Using our model

Let's explore how our model works by going into the _console_

  $ camping -C nuts.rb
  ** Starting console
  >>
 
Now it's waiting for your input, and will give you the answer when you press
Enter. Here's what I did, leaving out the boring answers. You should add your
own pages.

  >> Page = Nuts::Models::Page
 
  >> hiking = Page.new(:title => "Hiking")
  >> hiking.content = "You can also set the values like this."
  >> hiking.save

  >> page = Page.find_by_title("Hiking")
  => #<Nuts::Models::Page id: 1, ... >
  >> page = Page.find(1)
  => #<Nuts::Models::Page id: 1, ... >
  >> page.title
  >> page.content
  >> page.created_at
  >> page.updated_at
 
  >> Page.find_by_title("Fishing")
  => nil
 
  ## Page.create automatically saves the page for you.
  >> Page.create(:title => "Fishing", :content => "Go fish!")
 
  >> Page.count
  => 2
 
Now I have two pages: One about hiking and one about fishing.

== Wrapping it up

Wouldn't it be nice if we could show this wonderful our pages in a browser?
Update nuts.rb so it also contains something like this:

  module Nuts::Controllers
    class Pages
      def get
        # Only fetch the titles of the pages.
        @pages = Page.all(:select => "title")
        render :list
      end
    end
   
    class PageX
      def get(title)
        @page = Page.find_by_title(title)
        render :view
      end
    end
  end

  module Nuts::Views
    def list
      h1 "All pages"
      ul do
        @pages.each do |page|
          li do
            a page.title, :href => R(PageX, page.title)
          end
        end
      end
    end

    def view
      h1 @page.title
      self << @page.content
    end
  end
 
Here we meet our first _helper_:

  R(PageX, page.title)
 
This is the <em>reversed router</em> and it generates a URL based on a
controller. Camping ships with a few, but very useful, helpers and you can
easily add your owns. Have a look at Camping::Helpers for how you use these.
 
There's a lot of improvements you could do here. Let me suggest:

* Show when the page was created and last updated.
* What happens when the page doesn't exist?
* What should the front page show?
* Add a layout.
* Jazz it up a bit.

== The last touch

We have one major flaw in our little application. You can't edit or add new
pages. Let's see if we can fix that:

  module Nuts::Controllers
    class PageX
      def get(title)
        if @page = Page.find_by_title(title)
          render :view
        else
          redirect PageXEdit, title
        end
      end
     
      def post(title)
        # If it doesn't exist, initialize it:
        @page = Page.find_or_initialize_by_title(title)
        # This is the same as:
        # @page = Page.find_by_title(title) || Page.new(:title => title)
       
        @page.content = @input.content
        @page.save
        redirect PageX, title
      end
    end
   
    class PageXEdit
      def get(title)
        @page = Page.find_or_initialize_by_title(title)
        render :edit
      end
    end
  end
 
The core of this code lies in the new <tt>post</tt> method in the PageX
controller. When someone types an address or follows a link, they'll end up at
the <tt>get</tt> method, but you can easily create a form which rather sends
you to the <tt>post</tt> when submitted.

There are other names you can use, but they won't always work. So for now,
don't be fancy and just stick to <tt>get</tt> and <tt>post</tt>. We'll show
you how this really works later.

You might also notice that we use <tt>@input.content</tt>. The
<tt>@input</tt>-hash contains any extra parameters sent, like those in the
forms and those in the URL (<tt>/posts?page=50</tt>).

Here's an <tt>edit</tt>-view, but you can probably do better. See if you can
integrate all of this with what you already have.
 
  module Nuts::Views
    def edit
      h1 @page.title
      form :action => R(PageX, @page.title), :method => :post do
        textarea @page.content, :name => :content,
          :rows => 10, :cols => 50

        br
       
        input :type => :submit, :value => "Submit!"
      end
    end
  end
 

== Phew.

You've taken quite a few steps in the last minutes. You deserve a break. But
let's recap for a moment:

* Always place <tt>Camping.goes :App</tt> at the top of your file.
* Every route ends at a controller, but ...
* ... the controller only delegates the work.
* <tt>@input</tt> contains the extra parameters.
* The views are HTML disguised as Ruby.
* They can access the instances variables (those that starts with a single
  at-sign) from the controller.
* The models allows you to store all kinds of data.
* Place your models before your migrations.
* Helpers are helpful.

Unfortunately, the book stops here for now. Come back in a few months, or join
the mailing list to stay updated, and hopefully there's another chapter
waiting for you.
分享到:
评论

相关推荐

    web-dawn-camping:这是一个 Web 实验项目的集中存储库。 主要是给我的,但如果你有兴趣,你可以自己fork

    【标题】"Web-Dawn-Camping" 是一个用于汇集 Web 实验项目的开源存储库,旨在为个人学习和探索提供一个平台。项目的主要目的是为作者提供一个存放和管理其 Web 开发实验的地方,同时也欢迎感兴趣的开发者进行 fork ...

    Camping分析PPT学习教案.pptx

    Camping分析PPT学习教案.pptx

    Ruby元编程技术详解(Ruby Metaprogramming techniques)

    在Ruby中,每个对象都有一个与之关联的单例类,这个类只包含该对象的实例方法。通过`class ; self; end`可以访问到对象的单例类,这对于在运行时添加或修改对象的方法非常有用。`Kernel#singleton_class`方法可以...

    Camping Adventure Game 露营冒险游戏Unity 2d儿童家庭模拟游戏项目源码C#

    Camping Adventure Game 露营冒险游戏Unity2d儿童家庭模拟游戏项目源码C# 支持Unity版本2018.3.3f1及以上 准备好来一场真正的公路旅行周末冒险了吗?适合家庭的夏令营游戏就在这里,您可以通过许多激动人心的活动...

    基于Java核心技术的new-camping项目设计源码

    该项目是“新营地”系统的设计源码,基于Java核心技术构建,包含788个文件,涵盖376个Java源文件、110个Vue组件、91个JavaScript脚本、87个SVG矢量图形、45个XML配置文件、...该系统旨在提供一个全面的新营地解决方案。

    open-camping-data

    标题“open-camping-data”指的是一个与露营相关的数据集,该数据集是以JSON格式存储的,这使得数据可以通过编程方式轻松地进行读取、处理和分析。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,...

    go_camping

    一个新的Flutter项目。 入门 该项目是Flutter应用程序的起点。 如果这是您的第一个Flutter项目,那么有一些资源可以帮助您入门: 要获得Flutter入门方面的帮助,请查看我们的,其中提供了教程,示例,有关移动开发...

    bigoletexas:比较德州和thingz ..

    但是,网站本身主要包含在一个完整的Camping(旧的ruby http框架)文件BigOleTexas.rb中。 选择使用Camping的原因很简单:我们在DotGeek获得了一个免费的托管帐户,而Camping是(当时)他们提供的最可行的服务器。 ...

    opencampsitemap:Open Camping Map(基于 Openstreetmap 的世界露营地地图)

    总的来说,Open Camping Map是一个结合了Openstreetmap数据和JavaScript技术的优秀示例,它展示了如何利用开源资源创建实用且互动性强的Web应用。无论是户外探险者寻找露营地点,还是开发者学习地图应用的开发,都能...

    Tourist Camping Tycoon-开源

    通过精明的管理和策略规划,你可以将小规模的露营地发展成一个繁荣的旅游胜地。 这款游戏的独特之处在于其采用了jIsoEngine进行开发。jIsoEngine是一个用于构建2D游戏的开源Java库,它提供了高效的游戏渲染、场景...

    yellowstone-camping:露营地预订取消查找器(黄石国家公园)

    如何设置露营地搜索创建一个名为yellowstone-camping.env的文件并将其放置在此存储库的根目录中,您可以使用文件作为模板。 准备yellowstone-camping.env文件后,填写您的住宿详细信息和Pushover凭证: export ...

    camping:我最终项目的网站

    标题中的“camping:我最终项目的网站”表明这是一个关于野营主题的个人或团队最终完成的网站项目。这个项目可能是为了展示与露营、户外活动相关的资讯、攻略或者是个人对露营的兴趣分享平台。HTML标签则揭示了这个...

    flutter-camping-app

    在本文中,我们将深入探讨一个名为"flutter-camping-app"的项目,这是一个专为露营爱好者设计的应用程序用户界面。通过分析和解读这个项目的源代码,我们可以学习如何利用Dart语言和Flutter框架构建具有吸引力和实用...

    travel-lovers:Love TravelLovers是一个在线平台,同行的旅行者可以在这里结识志趣相投的人,共享地点并获得有关如何预订下一次改变人生的旅行的建议! :camping::globe_showing_Europe-Africa:

    :globe_showing_Europe-Africa: :camera: TravelLovers是一个在线平台,旅行者可以在这里结识志趣相投的人,共享地点并获得有关如何预订下一次改变人生的旅行的建议! :camping: :globe_showing_Europe-Africa: ...

    Tourist Trap

    【标题】"Tourist Trap" 可能是一个与设计或者排版相关的项目,可能是为了吸引游客或推广旅游目的地而创建的独特视觉元素。其中涉及到的主要知识点是“字体”,这是构成文字图形化表现的重要部分。 在设计领域,...

    recreation-gov-campsite-checker:报废creation.gov网站以检查露营地的可用性:camping::camping:

    $ python camping.py --start-date 2018-07-20 --end-date 2018-07-23 --parks 232448 232450 232447 232770 :cross_mark: TUOLUMNE MEADOWS: 0 site(s) available out of 148 site(s) :camping: LOWER PINES: 11 ...

    COLLABOARD_Android:我们是合作者:camping:

    标题中的"COLLABOARD_Android:我们是合作者:camping:"暗示这可能是一个针对Android平台的应用程序项目,名为COLLABOARD,其主题或特色可能是团队协作,特别是与"camping"相关的活动或者场景。这个应用可能设计用于...

    camping-general:露营管理

    在"camping-general-develop"这个文件中,很可能包含了与露营管理相关的Java代码或资源,可能是一个正在开发的应用程序,用于协助组织露营活动。这个应用可能使用了上述的Java技术和概念,如时间管理API、事件处理...

    darim::camping:支持客户端加密的私人日记服务

    它运行一个http服务器。 路由-表示层,它公开API,并将请求/响应数据传递给其他层。 服务-处理交易的业务层。 模型-可以访问数据库并定义数据结构的数据层。 客户端加密 Darim支持客户端加密,以保护用户的...

    CampingBot:Nate取笑了维京海盗Rob和安德鲁

    将camping_template.xml重命名为camping.xml 从@BotFather填写您的用户名和登录令牌 强烈建议将@BotFather的/ setinlinefeedback设置为Enabled,以便可以跟踪内联输入事件。 相依性 for UI 用于连接到电报的 选修...

Global site tag (gtag.js) - Google Analytics