Middlewares運作


application server <<---------------------------->>ruby web framework

                                  bunch of middlewares 


有意義的env hash資料


SERVER_NAME

REQUEST_METHOD

REQUEST_PATH

PATH_INFO

REQUEST_URI

QUERY_STRING

HTTP_REFERER 


在Nitrous下指令執行網頁


首先指定網址

git clone https//github.com/使用者名稱/資料夾 >>git clone GitHub網址

接線成功後

cd 資料夾/     >>cd 資料夾/

建立

bundle

安裝shotgum

gem install shotgun   >>安裝shotgun套件

shotgun指令在網頁上執行 Ruby port 3000

shotgun -o 0.0.0.0 -p 3000

Ctrl+C 停止連線

上方Preview選3000 


Http常做


 GetPostDeletePut/Patch 


常用套件


gem log4r

gem json

gem sqlite3

gem sinatra

gem sinatra-activerecord


程式碼


檔名:config.ru

require './framework'  <<載入framework.rb

 

class MyApp < Framework

  get '/' do         <<frameworkget方法

    self.inspect      <<根目錄顯示

  end

  get '/0118b' do      <<根目錄下0118b.rb

    'Hello'

  end

end

 

run MyApp         <<run MyApp類別

 

inspect參考網址:http://rails.ruby.tw/debugging_rails_applications.html#inspect

 

檔名:framework.rb

class Framework

  @@routes ={}  <<宣告類別變數routes

  class << self   self內容增加到class

    def find_route_and_execute(env)

      path = env['PATH_INFO']

      if @@routes.has_key?(path)  <<如果這pathkey對的話

        @@routes[path].call     <<OK的話執行call

      else

        nil      <<給一個白布

      end

    end

    def get(path,block)   <<傳入path&block

      @@routes[path.to_s] = block   <<path轉字串

    end

    def call(env)

      [200,    <<網頁代碼200意思是成功載入

        {"Content-Type" => "text/html"},     <<宣告html文件

        [find_route_and_execute(env)]       <<載入內容與執行

      ]

    end

  end

end

 

<<參考網址:http://sls.weco.net/node/10732


檔名:configa.ru

require './frameworka'

 

class MyApp < Framework

  get /\/books\/(\d+?)$/ do |id|   <<網址/books/傳入變數

    p "request" + request.inspect

    p "params" + params.inspect

    "This is book id = #{id},request = #{request},foo = #{params}"

  end

  get /\/0118b/ do   <<網址/0118b.rb

    'Hello'

  end

end

 

run MyApp

 

檔名:frameworka.rb

class Framework

  @@routes ={}

  class << self

    def params

      @@params

    end

    def request

      @@request

    end

    def find_route_and_execute(env)

      path = env['PATH_INFO']

      @@routes.each do |path_exp,code_block|

        var_arr = path.scan(path_exp).flatten    <<scan轉成陣列,flatten變回一維陣列

        unless var_arr.empty?

          return code_block.call(*var_arr)

        end

      end

      ""

    end

    def get(path,block)

      @@routes[path] = block

    end

    def call(env)

      @@request = Rack::Request.new(env)

      @@params = @@request.params

      [200,

        {"Content-Type" => "text/html"},

        [find_route_and_execute(env)]

      ]

    end

  end

end


檔名:g0118.ru

require 'bundler'

Bundler.setup

Bundler.require

 

class MyApp < Sinatra::Base

 

  get '/0118b/:name'

  "Hello, #{params[:name]}"

  end

 

  get '/' do

    'Hello'

  end

 

  post '/books' do

    'post books'

  end

 

end

 

run MyApp


檔名:gemfileb.ru

require 'bundler'

Bundler.setup

Bundler.require

require './gemfilea'

 

 

class MyApp < Framework

 

  get /\/books\/(\d+?)$/ do |id|

    render 'show.html', layout_path: 'views/layout2.erb', locals: {id: id}

  end

 

  get /\/0118b/ do

    'Hello'

  end 

end

 

run MyApp

 

檔名:gemfilea.rb

class Framework

  @@routes = {}

  class << self

    def params

      @@params

    end

 

    def request

      @@request

    end

 

    DEFAULT_LAYOUT_PATH = 'views/layout.erb'

    # render('index, foo: "bar")

    def render(view_path, options = {})

      layout_path = options.delete(:layout_path) || DEFAULT_LAYOUT_PATH   <<網頁路徑

      locals_hash = options.delete(:locals) || {}    <<網頁ID

      template_path = File.join("views", "#{view_path}.erb")     <<載入網頁要在views下找某某.erb

      view_buffer = Tilt::ERBTemplate.new(template_path).render(self, locals_hash)     <<利用ERB把載入檔案路徑和網頁路徑和ID記錄下來 

      Tilt::ERBTemplate.new(layout_path).render(self, locals_hash) do

        view_buffer

      end

    end

 

    def find_route_and_execute(env)

      path = env['PATH_INFO']

      @@routes.each do |path_exp, code_block|

        var_arr = path.scan(path_exp).flatten

        unless var_arr.empty?

          return code_block.call(*var_arr)

        end

      end

      ""

    end

   

    def get(path, &block)

      @@routes[path] = block

    end

   

    def call(env)

      @@request = Rack::Request.new(env)

      @@params = @@request.params

      [200,

        {"Content-Type" => "text/html"},

        [find_route_and_execute(env)]

      ]

    end

  end

end

 

檔名:layout.erb

路徑:views/layout.erb  <<views是資料夾

<!DOCTYPE html>

<html>

<head>

  <title>Album</title>

</head>

<body>

 

<%= yield %>

 

</body>

</html>

 

檔名:layout2.erb

路徑:views/layout2.erb

<!DOCTYPE html>

<html>

<head>

  <title>Books</title>

</head>

<body>

 

<%= yield %>

 

</body>

</html>

 

檔名:show.html.erb

路徑:views/show.html.erb

You are getting book with id<%=id%>

<pre>

<%=params.inspect%>

</pre>


檔名:img_list.rb

class ImgList < Sinatra::Base

 

  Images = {

    "1" => {

      url: 'http://i.imgur.com/LIPAV4D.jpg', title: 'The incredible paintings of Rob Gonsalves 1'},

    "2" => {

     url: 'http://i.imgur.com/y40a93x.jpg', title: 'Image2'},

    "3" => {

      url: 'http://i.imgur.com/hswP6Mz.png', title: 'A moment of silence'

    }

  }

 

  get '/imgs' do

    erb :'index.html'

  end

 

  get '/imgs/:id' do |imgid|

    Images.each do |id, img|

      if id.to_i == imgid.to_i

        @img = img

        break

      end

    end

    erb :'show.htmla'

  end

end

 

檔名:show.htmla.erb

路徑:views/show.htmla.erb

<div>

  Title<%=@img[:title]%><BR/>

    <img src="<%=@img[:url]%>" width="400"/>

</div>

 

檔名:index.html.erb

路徑:views/index.html.erb

<ul>

  <%Images.each do |img|%>

  <li>Title<%=img[:title]%><BR/>

    <img src="<%=img[:url]%>" width="400"/>

  </li>

  <%end%>

</ul>


檔名:session.ru

require 'bundler'

Bundler.setup

Bundler.require

require './auth_app'

 

run AuthApp

 

檔名:auth_app.rb

class AuthApp < Sinatra::Base

  configure do

    enable :sessions

    set :session_secret, "nljksadlkasjdaskjd;lasdjlkasjdklasjdals;hdasdhsdas;hdyqudqwudajs"

 

    logger = Log4r::Logger.new "app"

    logger.outputters << Log4r::Outputter.stderr

    file_logger = Log4r::FileOutputter.new('logtest', filename: 'development.log')

    #file_logger.formatter = Log4r::PatternFormatter.new(pattern: ' [%1] %d :: %m ')

    logger.outputters << file_logger

 

  end

 

  Users = [

    {

      email: 'ryudo@5xruby.tw',

      password: '1qaz2wsx'

    },{

      email: 'eddie@5xruby.tw',

      password: '12345678'

    }

  ]

 

  Images = [

    {

      url: 'http://i.imgur.com/LIPAV4D.jpg', title: 'The incredible paintings of Rob Gonsalves 1'},

    {

     url: 'http://i.imgur.com/y40a93x.jpg', title: 'Image2'},

    {

      url: 'http://i.imgur.com/hswP6Mz.png', title: 'A moment of silence'

    }

  ]

 

  helpers do

    def logger

      @logger ||= Log4r::Logger['app']

    end

  end

 

  before do

    logger.info "#### BEFORE BLOCK########"

    @current_user = session[:current_user]

  end

 

  before '/imgs' do

    unless session[:current_user]

      halt 'Not authorized'

    end

  end

 

  get '/imgs' do

    erb :'index.html'

  end

 

  get '/login' do

    erb :'login.html'

  end

  post '/login' do

    Users.each do |user|

      if user[:email] == params["email"] && user[:password] == params[:password]

        @current_user = user

        session[:current_user] = user

        return erb(:'login_success.html')

      end

    end

    redirect '/login'

  end

end

 

檔名:login.html.erb

路徑:views/ login.html.erb

<form action="/login" method="post">

  <input type="email" name="email" />

  <input type="password" name="password" />

  <input type="submit" value="登入"/>

</form>

 

檔名:login_success.html.erb

路徑:views/ login_success.html.erb

<div>

  Hello<%=@current_user[:email]%>

</div>

arrow
arrow
    全站熱搜

    o迷苓o 發表在 痞客邦 留言(0) 人氣()