Ruby w / Sinatra: what is equivalent to .js.erb from rails?

.js.erb are good because you can use them to replace parts of the page without having to leave the current page, which gives a cleaner and unsolicited feel on the site / application.

Is there a way to use them in sinatra? or equivalent?

+3
source share
3 answers

Based on your description, I assume that your desire is for parts of the page to be edited and replaced through AJAX. If this is not correct, please clarify.

Sinatra, ( ) AJAXFetch jQuery library , . , AJAX, . AJAXFetch AJAX fetch/swap , JS , .

/partials.rb

require 'sinatra/base'
module Sinatra
  module PartialPartials
    ENV_PATHS = %w[ REQUEST_PATH PATH_INFO REQUEST_URI ] 
    def spoof_request( uri, headers=nil ) 
      new_env = env.dup 
      ENV_PATHS.each{ |k| new_env[k] = uri.to_s } 
      new_env.merge!(headers) if headers
      call( new_env ).last.join 
    end
    def partial( page, variables={} )
      haml page, {layout:false}, variables
    end
  end
  helpers PartialPartials
end

/bug.rb

get '/bug/:bug_id' do
  if @bug = Bug[params[:bug_id]]
    # ...
    haml :bug
  end
end

# Generate routes for each known partial
partials = %w[ bugdescription bughistory bugtitle fixer
               pain project relatedbugs status tags version votes ]
partials.each do |part|
  [ part, "#{part}_edit" ].each do |name|
    get "/partial/#{name}/:bug_id" do
      id = params[:bug_id]
      login_required
      halt 404, "(no bug ##{id})" unless @bug = Bug[id]
      partial :"_#{name}"
    end
  end
end

post "/update_bug/:partial" do
  id = params[:bug_id]
  unless params['cancel']=='cancel'
    # (update the bug based on fields)
    @bug.save
  end
  spoof_request "/partial/#{params[:partial]}/#{id}", 'REQUEST_METHOD'=>'GET'
end

/bug.haml

#main
  #bug.section
    = partial :_bugtitle
    .section-body
      = partial :_bugdescription
   <!-- many more partials used -->

/_bugtitle.haml

%h1.ajaxfetch-andswap.editable(href="/partial/bugtitle_edit/#{@bug.pk}")= title

/_bugtitle_edit.haml

%form.ajaxfetch-andswap(method='post' action='/update_bug/bugtitle')
  %input(type="hidden" name="bug_id" value="#{@bug.id}")
  %h1
    %input(type="text" name="name" value="#{h @bug.name}")
    %span.edit-buttons
      %button(type="submit") update
      %button(type="submit" name="cancel" value="cancel") cancel
+2

.js , erb(). A la ( mypage.js.erb):

erb "mypage.js".to_sym

, .

+3

. , . erb , sinatra.

0

Source: https://habr.com/ru/post/1789120/


All Articles