草庐IT

javascript - rails 上的 ruby || Jquery 和 JavaScript 库不工作

coder 2024-07-19 原文

我在 Codepen 上创建了一个页面,稍后将添加到我的 Ruby on Rails 应用程序( https://codepen.io/salman15/pen/evQVLV ),所有代码都可以正常工作。

创建页面后,我尝试使用 spree 将页面添加到我的 Ruby on Rails 应用程序(它在 Cloud 9 上运行 https://consulegem-salman15.c9users.io/ “您阅读本文时服务器可能未离线”)。我通过以下方式完成了此操作:

第 1 步:将 html 代码添加到 index.html.erb

第 2 步:将 CSS CDN 添加到 _head.html.erb

第 3 步:下载所有 JavaScript 库并将它们添加到以下文件夹路径 -> app -> assets -> javascripts -> frontend -> store

第 4 步:将以下代码行添加到我的 all.js 文件(在前端文件夹中)

//= require_tree

此时我的代码应该可以正常工作,但它没有。

Uncaught TypeError: $(...).easeScroll is not a function
    at script.self-a9cf77dbbd3e521fbb44b192f7d525c508a4a35eee8e827785ebb4ce329092f5.js?body=1:341

Uncaught TypeError: $(...).logosDistort is not a function
    at HTMLDocument.<anonymous> (script.self-a9cf77dbbd3e521fbb44b192f7d525c508a4a35eee8e827785ebb4ce329092f5.js?body=1:220)
    at j (jquery.min.self-6806c88afe0840c35208894c4ceba911154f696b624614b30b884298c2c3e00d.js?body=1:3)
    at Object.fireWith [as resolveWith] (jquery.min.self-6806c88afe0840c35208894c4ceba911154f696b624614b30b884298c2c3e00d.js?body=1:3)
    at Function.ready (jquery.min.self-6806c88afe0840c35208894c4ceba911154f696b624614b30b884298c2c3e00d.js?body=1:3)
    at HTMLDocument.I (jquery.min.self-6806c88afe0840c35208894c4ceba911154f696b624614b30b884298c2c3e00d.js?body=1:3)

13:10:27:369 (ScrollScene) -> ERROR: Element defined in option "triggerElement" was not found: #section-6

13:10:27:373 (ScrollScene) -> ERROR: Element defined in option "triggerElement" was not found: #section-6

13:10:27:373 (ScrollScene) -> ERROR: Invalid value for option "triggerHook":  .charger

13:10:27:374 (ScrollScene) -> ERROR: Element defined in option "triggerElement" was not found: #section-7

13:10:27:375 (ScrollScene) -> ERROR: Element defined in option "triggerElement" was not found: #section-7

令我烦恼的是,完全相同的代码和完全相同的库似乎无法在我的 Ruby on Rails 应用程序上运行,这就是我的幻觉,为什么?

is not a function错误是因为代码无法识别,通常是因为库没有加载。然而,我在加载页面并加载所有库后检查了源页面。

TweenMax 错误也是我的幻影,因为它是相同的库和相同的代码。

我已经尝试了几种解决方案,比如将库代码添加到我的 script.js 中,它似乎可以工作,但这是一个不合适的解决方案。

我想我已经准备好了所有需要的信息和代码,但如果您还需要,请随时询问。

总结一下我的问题:

问题:我的 Jquery 库似乎不起作用

问题:为什么?

script.js

    //MENU

    var wrap = $("#main-nav-bar");

    wrap.on("scroll", function(e) {
      if (this.scrollTop > 147) {
        wrap.addClass("fix-search");
      } else {
        wrap.removeClass("fix-search");
      }
    });

    //MENU END

    //TWEENMAX

    /* triggerHook: "onEnter" "onLeave" "onCenter"; */
    var controller = new ScrollMagic();

    // Section 6
    new ScrollScene({
      triggerElement: "#section-6",
      duration: 300,
      triggerHook: 0.2
    })
      .setTween(TweenMax.to(".charging", 1, { opacity: "1" }))
      .addTo(controller);

    new ScrollScene({
      triggerElement: "#section-6",
      duration: 600,
      triggerHook: ".charger"
    })
      .setTween(TweenMax.to(".charger", 1, { top: "766px" }))
      .addTo(controller);

    new ScrollScene({
      triggerElement: "#section-7",
      duration: 200,
      triggerHook: 0.7
    })
      .setTween(TweenMax.to(".red-light", 1, { opacity: "1" }))
      .addTo(controller);

    new ScrollScene({
      triggerElement: "#section-7",
      duration: 400,
      triggerHook: 0.5
    })
      .setTween(TweenMax.to(".front-phone", 1, { opacity: "1" }))
      .addTo(controller);

    //TWEENMAX END

    //PARALLAX

    (function() {
      var parallax = document.querySelectorAll(".parallax"), speed = 0.3;

      window.onscroll = function() {
        [].slice.call(parallax).forEach(function(el, i) {
          var windowYOffset = window.pageYOffset,
            elBackgrounPos = "0 " + windowYOffset * speed + "px";

          el.style.backgroundPosition = elBackgrounPos;
        });
      };
    })();

    // END PARALLAX

    //Scrolling

    $(document).ready(function() {
      //$("body").smoothWheel();
    });

    (function($) {
      var self = this,
        container,
        running = false,
        currentY = 0,
        targetY = 0,
        oldY = 0,
        maxScrollTop = 0,
        minScrollTop,
        direction,
        onRenderCallback = null,
        fricton = 0.96, // higher value for slower deceleration
        vy = 0,
        stepAmt = 1,
        minMovement = 0.1,
        ts = 0.1;

      var updateScrollTarget = function(amt) {
        targetY += amt;
        vy += (targetY - oldY) * stepAmt;

        oldY = targetY;
      };
      var render = function() {
        if (vy < -minMovement || vy > minMovement) {
          currentY = currentY + vy;
          if (currentY > maxScrollTop) {
            currentY = vy = 0;
          } else if (currentY < minScrollTop) {
            vy = 0;
            currentY = minScrollTop;
          }

          container.scrollTop(-currentY);

          vy *= fricton;

          //   vy += ts * (currentY-targetY);
          // scrollTopTweened += settings.tweenSpeed * (scrollTop - scrollTopTweened);
          // currentY += ts * (targetY - currentY);

          if (onRenderCallback) {
            onRenderCallback();
          }
        }
      };
      var animateLoop = function() {
        if (!running) return;
        requestAnimFrame(animateLoop);
        render();
        //log("45","animateLoop","animateLoop", "",stop);
      };
      var onWheel = function(e) {
        e.preventDefault();
        var evt = e.originalEvent;

        var delta = evt.detail ? evt.detail * -1 : evt.wheelDelta / 40;
        var dir = delta < 0 ? -1 : 1;
        if (dir != direction) {
          vy = 0;
          direction = dir;
        }

        updateScrollTarget(delta);
      };

      window.requestAnimFrame = (function() {
        return (
          window.requestAnimationFrame ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame ||
          window.oRequestAnimationFrame ||
          window.msRequestAnimationFrame ||
          function(callback) {
            window.setTimeout(callback, 1000 / 60);
          }
        );
      })();

      /*
         * http://jsbin.com/iqafek/2/edit
         */
      var normalizeWheelDelta = (function() {
        // Keep a distribution of observed values, and scale by the
        // 33rd percentile.
        var distribution = [], done = null, scale = 30;
        return function(n) {
          // Zeroes don't count.
          if (n == 0) return n;
          // After 500 samples, we stop sampling and keep current factor.
          if (done != null) return n * done;
          var abs = Math.abs(n);
          // Insert value (sorted in ascending order).
          outer: do {
            // Just used for break goto
            for (var i = 0; i < distribution.length; ++i) {
              if (abs <= distribution[i]) {
                distribution.splice(i, 0, abs);
                break outer;
              }
            }
            distribution.push(abs);
          } while (false);
          // Factor is scale divided by 33rd percentile.
          var factor = scale / distribution[Math.floor(distribution.length / 3)];
          if (distribution.length == 500) done = factor;
          return n * factor;
        };
      })();

      //END SCROLLING

      //MOVING PHONE
      $.fn.smoothWheel = function() {
        //  var args = [].splice.call(arguments, 0);
        var options = jQuery.extend({}, arguments[0]);
        return this.each(function(index, elm) {
          if (!("ontouchstart" in window)) {
            container = $(this);
            container.bind("mousewheel", onWheel);
            container.bind("DOMMouseScroll", onWheel);
            currentY = targetY = 0;
            minScrollTop =
              container.get(0).clientHeight - container.get(0).scrollHeight;
            if (options.onRender) {
              onRenderCallback = options.onRender;
            }
            if (options.remove) {
              log("122", "smoothWheel", "remove", "");
              running = false;
              container.unbind("mousewheel", onWheel);
              container.unbind("DOMMouseScroll", onWheel);
            } else if (!running) {
              running = true;
              animateLoop();
            }
          }
        });
      };

      //END MOVING PHONE
    })(jQuery);

    //fade in
    var $animation_elements = $(".animation-element");
    var $window = $(window);

    function check_if_in_view() {
      var window_height = $window.height();
      var window_top_position = $window.scrollTop();
      var window_bottom_position = window_top_position + window_height;

      $.each($animation_elements, function() {
        var $element = $(this);
        var element_height = $element.outerHeight();
        var element_top_position = $element.offset().top;
        var element_bottom_position = element_top_position + element_height;

        //check to see if this current container is within viewport
        if (
          element_bottom_position >= window_top_position &&
          element_top_position <= window_bottom_position
        ) {
          $element.addClass("in-view");
        } else {
          $element.removeClass("in-view");
        }
      });
    }

    $window.on("scroll resize", check_if_in_view);
    $window.trigger("scroll");

    var particles = true,
      particleDensity,
      options = {
        effectWeight: 1,
        outerBuffer: 1.08,
        elementDepth: 220
      };

    $(document).ready(function() {
      $(".section-0").logosDistort(options);

      if (particles) {
        particleDensity = window.outerWidth * 7.5;
        if (particleDensity < 13000) {
          particleDensity = 13000;
        } else if (particleDensity > 20000) {
          particleDensity = 20000;
        }
        return $("#particle-target").particleground({
          dotColor: "#1ec5ee",
          lineColor: "#0a4e90",
          density: particleDensity.toFixed(0),
          parallax: false
        });
      }
    });

    $(document).ready(function() {
      /** 
         * This part does the "fixed navigation after scroll" functionality
         * We use the jQuery function scroll() to recalculate our variables as the 
         * page is scrolled/
         */
      $(window).scroll(function() {
        var window_top = $(window).scrollTop() + 12; // the "12" should equal the margin-top value for nav.stick
        var div_top = $("#nav-anchor").offset().top;
        if (window_top > div_top) {
          $("nav").addClass("stick");
        } else {
          $("nav").removeClass("stick");
        }
      });

      /**
         * This part causes smooth scrolling using scrollto.js
         * We target all a tags inside the nav, and apply the scrollto.js to it.
         */
      $("nav a").click(function(evn) {
        evn.preventDefault();
        $("html,body").scrollTo(this.hash, this.hash);
      });

      /**
         * This part handles the highlighting functionality.
         * We use the scroll functionality again, some array creation and 
         * manipulation, class adding and class removing, and conditional testing
         */
      var aChildren = $("nav li").children(); // find the a children of the list items
      var aArray = []; // create the empty aArray
      for (var i = 0; i < aChildren.length; i++) {
        var aChild = aChildren[i];
        var ahref = $(aChild).attr("href");
        aArray.push(ahref);
      } // this for loop fills the aArray with attribute href values

      $(window).scroll(function() {
        var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
        var windowHeight = $(window).height(); // get the height of the window
        var docHeight = $(document).height();

        for (var i = 0; i < aArray.length; i++) {
          var theID = aArray[i];
          var divPos = $(theID).offset().top; // get the offset of the div from the top of page
          var divHeight = $(theID).height(); // get the height of the div in question
          if (windowPos >= divPos && windowPos < divPos + divHeight) {
            $("a[href='" + theID + "']").addClass("nav-active");
          } else {
            $("a[href='" + theID + "']").removeClass("nav-active");
          }
        }

        if (windowPos + windowHeight == docHeight) {
          if (!$("nav li:last-child a").hasClass("nav-active")) {
            var navActiveCurrent = $(".nav-active").attr("href");
            $("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
            $("nav li:last-child a").addClass("nav-active");
          }
        }
      });
    });

    //smooth anchors
    // Select all links with hashes
    $('a[href*="#"]')
      // Remove links that don't actually link to anything
      .not('[href="#"]')
      .not('[href="#0"]')
      .click(function(event) {
        // On-page links
        if (
          location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
          && 
          location.hostname == this.hostname
        ) {
          // Figure out element to scroll to
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
          // Does a scroll target exist?
          if (target.length) {
            // Only prevent default if animation is actually gonna happen
            event.preventDefault();
            $('html, body').animate({
              scrollTop: target.offset().top
            }, 1000, function() {
              // Callback after animation
              // Must change focus!
              var $target = $(target);
              $target.focus();
              if ($target.is(":focus")) { // Checking if the target was focused
                return false;
              } else {
                $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
                $target.focus(); // Set focus again
              };
            });
          }
        }

  });

//end smooth anchors

index.html.erb

  <div id="sidebar">
  <div id="nav-anchor"></div>
  <nav>
    <ul>
      <li>
        <a href="#section-1">
          <div class="ball"></div><span id="link">Top</span></a>
      </li>
      <li>
        <a href="#section-2">
          <div class="ball"></div><span id="link">Design</span></a>
      </li>
      <li>
        <a href="#section-4">
          <div class="ball"></div><span id="link">Vermogen</span></a>
      </li>
      <li>
        <a href="#section-7">
          <div class="ball"></div><span id="link">Iris scanner</span></a>
      </li>
      <li>
        <a href="#section-8">
          <div class="ball"></div><span id="link">Fingerprint Scanner</span></a>
      </li>
      <li>
        <a href="#section-5">
          <div class="ball"></div><span id="link">Camera</span></a>
      </li>
      <li>
        <a href="#section-6">
          <div class="ball"></div><span id="link">Batterij</span></a>
      </li>
      <li>
        <a href="#section-9">
          <div class="ball"></div><span id="link">Software</span></a>
      </li>
    </ul>
  </nav>
</div>

<div class="section-0">
  <div class="phone-container">
    <div class="phone-front" id="layer-one"></div>
  </div>
</div>

<section class="section-1 parallax parallax-1" id="section-1">


  <div class="container" id="section-1">


    <div class="text-block animation-element">
      <h1>De toekomst is nu</h1>
      <p>"De Volks Phone is een geweldig hi-end toestel voor een betaalbare prijs."<br> — "Telegraaf"</p><br>
      <div class="pre-order-button">
        <a href="#section-9"> Pre-order</a>
      </div>
    </div>
  </div>

</section>
<section class="section-2" id="section-2">
  <div class="container">
    <div class="left-half" id="left-half-home">
      <div class="text-block animation-element">

        <h1>“De perfecte balans tussen staal en glaswerk”</h1>

      </div>
    </div>
    <div class="right-half" id="right-half-home">
      <div class="rear-phone animation-element bounce-up">

      </div>
    </div>
  </div>
</section>
<section class="section-3 parallax parallax-2" id="section-3">
  <div class="container">
    <h1>Ons Volk</h1>
  </div>
</section>
<section class="section-4" id="section-4">
  <div class="container">
    <div class="top-part" id="left-half-home">
      <div class="text-block animation-element">

        <h1>Beter. Sneller. Uniek.</h1>


      </div>
    </div>
    <div class="middle-part" id="right-half-home">
      <div class="rear-phone animation-element slide-right">

      </div>
    </div>
    <div class="bottom-part">
      <div class="text-block ">

        <ul>

          <li class="spec-left">
            <h1>6GB</h1>
            <img src="http://sterntelecom.com/img/phones/ram-memory.png">
            <h4>RAM</h4></li>

          <li class="spec-center">

            <h1> 4.2 Mghz </h1>
            <img src="http://sterntelecom.com/img/phones/cpu.png">
            <h4>Deca core CPU</h4></li>

          <li class="spec-right">
            <h1>64GB</h1>
            <<img src="http://sterntelecom.com/img/phones/hard-drive.png">
              <h4>Opslag</h4></li>

          <li class="spec-right">
            <h1>5.5 Inch</h1>
            <img src="http://sterntelecom.com/img/phones/inch.png">-
            <h4>Scherm</h4></li>
        </ul>

      </div>
    </div>
  </div>
</section>
<section class="section-7" id="section-7">
  <div class="container">
    <div class="intro-text">
      <h1>Wat science fiction was in nu werkelijkheid.</h1>
      <h2>Maak kennis met de ultra-moderne functie van uw Volks Phone: De irisscanner</h2>
    </div>
    <div class="red-light"></div>
    <div class="front-phone left-half" id="left-half-home">
      <div class="screen" id="screen-section-7">
      </div>
    </div>
    <div class="right-half" id="right-half-home">
      <div class=" animation-element ">
        <div class="text-block animation-element ">

          <h1>Veilig</h1>
          <p>Elk iris vertoont een uniek patroon. Met de irisscanner bent u verzekerd van veiligheid.</p>

        </div>
        <div class="text-block animation-element ">

          <h1>Ook in het donker</h1>
          <p>Met de infrarood iris scanner herkent de Volks Phone uw irissen ook in het donker.</p>

        </div>
        <!--<div class="text-block animation-element ">

          <h1>High-end telefoon voor een Low prijs</h1>
          <p>"The volks is the rare kind of phone that I can recommend without reservations."<br> — The Verge</p>

        </div>-->
      </div>
    </div>
  </div>
</section>
<section class="section-8" id="section-8">
  <div class="container">
    <div class="left-half" id="left-half-home">
      <div class="text-block">

        <h1>Fingerprint scanner</h1><br>
        <p>Ontgrendel de Volks Phone binnen 0.4 seconden met met de super snelle vingerafdrukscanner</p>

      </div>
    </div>
    <div class="right-half animation-element bounce-up" id="right-half-home">

    </div>
  </div>
</section>
<section class="section-5" id="section-5">
  <div class="container">
    <div class="top-part" id="left-half-home">
      <div class="text-block">

        <h1>Haarscherpe foto's</h1><br>
        <p>16-mp back-camera, 13-mp front-camera.</p>

      </div>
    </div>
    <div class="middle-part" id="right-half-home">


    </div>
    <div class="bottom-part">
      <div class="text-block animation-element bounce-up">

      </div>
    </div>
  </div>
</section>
<section class="section-6" id="section-6">
  <div class="container">
    <div class="front-phone left-half" id="left-half-home">
      <div class="screen">
        <div class="animation-element charging" id="charging">
          <h1>Fast Charging</h1>
          <div class="animation-element battery"></div>
        </div>
      </div>
    </div>
    <div class="charger">
    </div>
    <div class="right-half" id="right-half-home">
      <div class=" animation-element bounce-up">
        <div class="text-block animation-element">

          <h1>Groot</h1>
          <p>Met een capaciteit van 3250Mah biedt Volks u een bovengemiddeld batterij vermogen.</p>

        </div>
        <div class="text-block animation-element">

          <h1>Snel</h1>
          <p>Via de fast-charging functie is de Volks Phone binnen 45minuten volledig opgeladen
          </p>

        </div>
        <div class="text-block animation-element">

          <h1>Zuinig</h1>
          <p>De Deca-core processor zorgt ervoor dat het toestel alleen op volle energie presteert wanneer dat nodig is.
          </p>

        </div>
      </div>
    </div>
  </div>
</section>
<section class="section-9" id="section-9">
  <div class="container">
    <div class="top-part" id="left-half-home">
      <div class="text-block animation-element">

        <h1>Simpliciteit op z'n fijnst</h1>
        <p>"The volks is the rare kind of phone that I can recommend without reservations."<br> — The Verge</p>
        <div class="pre-order-button">
          <a href=""> Pre-order</a>
        </div>
      </div>

    </div>
    <div class="middle-part" id="right-half-home">
      <div class="screens">
      </div>
    </div>
  </div>
  <div class="arrow-up">
    <a href="#section-1"><img src="http://sterntelecom.com/img/phones/arrowhead.png"></a>
  </div>
</section>

更新(添加请求的文件)

application.js

  // This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require spree/frontend

//= require_tree .
//= require spree/frontend/spree_auth
//= require spree/frontend/spree_braintree_vzero



//= require jquery

//= require jquery_ujs

//= require turbolinks

//= require_tree

//= require_jquery.min

//= require_jquery-3.2.1.min

//= require_jquery.easeScroll

//= require_jquery.logosDistort.min

//= require_jquery.particleground.min

//= require_jquery.jquery.scrollmagic.min


//= require 'greensock/TweenLite'
//= require 'greensock/easing/EasePack'
//= require 'greensock/jquery.gsap.js'

_head.html.erb

<meta charset="utf-8">
<title>Volks - Het volk's toestel</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1" name="viewport">

<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css'>
<link rel='stylesheet prefetch' href='https://www.jqueryscript.net/demo/jQuery-Plugin-For-3D-Perspective-Transforms-On-Mousemove-LogosDistort/assets/css/perspectiveRules.css'>

<%== meta_data_tags %>
<%= canonical_tag(current_store.url) %>
<%= favicon_link_tag 'volks-logo.png' %>
<%= stylesheet_link_tag 'spree/frontend/all', media: 'screen' %>
<%= csrf_meta_tags %>


<%= javascript_include_tag 'spree/frontend/all' %>


<!--[if lt IE 9]>
  <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.6/html5shiv.min.js"></script>
<![endif]-->
<%= yield :head %>

更新 2(更改了 application.js 文件)

//= require jquery

//= require jquery_ujs

//= require turbolinks

//= require_jquery.min

//= require_jquery-3.2.1.min

//= require_jquery.easeScroll

//= require_jquery.logosDistort.min

//= require_jquery.particleground.min

//= require_jquery.jquery.scrollmagic.min


//= require spree/frontend/spree_auth
//= require spree/frontend/spree_braintree_vzero

回答

您可以在下面的答案中找到答案,但这不是答案的唯一部分。答案的最后一部分在 CSS 中,我的 body 发生冲突导致部分错误。因此,如果您遇到同样的问题,请确保您的库加载到正确的位置(对我来说是底部)和正确的顺序。还要确保您的 CSS 也不会导致任何错误。

最佳答案

根据您粘贴的文件,库的加载顺序错误。我怀疑应将以下行移至您的 application.js 的末尾 list ,以确保它仅在所有 jQuery 之后加载插件是。像这样的东西:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

请注意,require_tree不保证自定义脚本的加载顺序。因此,如果一个脚本依赖于另一个脚本,您仍然会遇到这些问题。您应该尝试编写独立脚本,这样执行顺序就无关紧要了。如果您绝对必须编写相互依赖的脚本,那么您应该倾向于在 list 中以正确的顺序手动导入它们。

此外,您的导入看起来不对。您似乎已经三次导入 jQuery。您应该粘贴 <head> 的内容在开发模式下在最终呈现的页面中添加标记,以确保这确实有效。

//= require_jquery.min <-- second import!
//= require_jquery-3.2.1.min <-- third import!
//= require_jquery.easeScroll
//= require_jquery.logosDistort.min
//= require_jquery.particleground.min
//= require_jquery.jquery.scrollmagic.min

尝试:

//= require jquery.easeScroll

将相关 gem 添加到您的 Gemfile 后,当然。

关于javascript - rails 上的 ruby || Jquery 和 JavaScript 库不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45649706/

有关javascript - rails 上的 ruby || Jquery 和 JavaScript 库不工作的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  4. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  5. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  6. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  7. ruby-on-rails - rails : keeping DRY with ActiveRecord models that share similar complex attributes - 2

    这似乎应该有一个直截了当的答案,但在Google上花了很多时间,所以我找不到它。这可能是缺少正确关键字的情况。在我的RoR应用程序中,我有几个模型共享一种特定类型的字符串属性,该属性具有特殊验证和其他功能。我能想到的最接近的类似示例是表示URL的字符串。这会导致模型中出现大量重复(甚至单元测试中会出现更多重复),但我不确定如何让它更DRY。我能想到几个可能的方向...按照“validates_url_format_of”插件,但这只会让验证干给这个特殊的字符串它自己的模型,但这看起来很像重溶液为这个特殊的字符串创建一个ruby​​类,但是我如何得到ActiveRecord关联这个类模型

  8. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  9. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  10. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

随机推荐