【问题标题】:Mix ruby code with js.coffee script将 ruby​​ 代码与 js.coffee 脚本混合
【发布时间】:2012-11-18 22:25:16
【问题描述】:

我的视图上有 ajax 链接,我想在它们被发送到实际操作之前检查密码,因为我使用的是设计控制器,所以我仅限于使用特定的密码检查。 以下是我希望用于验证的咖啡脚本。

. "some_action", :info => n.id },class: "css_class",:remote => true %>

我正在使用上面的链接

我正在寻找以下类型的代码。

$("a.css_class").live "click", ->
      password_variable = prompt("Enter password", "password")
      if |ruby-code|current_user.valid_password?(password_variable)|ruby-code|
        true
      else
        alert "You entered wrong password"
        false

ruby 代码将如何与咖啡脚本组合一起使用。

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax coffeescript


    【解决方案1】:

    如果它是您的静态资产的代码,那么很明显您将无法将一些服务器端动态放入其中。它将被转换为纯 JavaScript-sn-p 并放入您应用的 public 文件夹中。

    如果您的视图名为 *.coffee,那么您已经完成了所有准备工作。以这种方式命名的视图将使用 ERb 引擎自动进行预处理(通过<%= ... %>):

    视图/some/thing.coffee:

    alert "Server's time is <%= Time.now %>"
    

    【讨论】:

    • 我认为,那么最好先将其重定向到另一个动作,然后使用 render :js => "function();" 从那里调用一个函数怎么说?
    • @NishutoshSharma 我想制作一些“取消”ajax 动作。然后,您可以在提示字段中输入密码后通过 ajax 访问它。因此,您可以制作link_to_function api.rubyonrails.org/classes/ActionView/Helpers/…,而不是制作远程link_to。它会询问密码并发出一些非 GET 请求来取消订单。
    • 在 Rails 4 中,我发现有必要将文件命名为 views/some/thing.coffee.erb 以便处理嵌入的 Ruby 语句。这对于嵌入存储在 secrets.yml 中的 Rails 4 的配置非常有用。
    【解决方案2】:

    我也有同样的疑问。

    背景:

    我正在为我的公司编写 ERP。它使用西班牙语、英语和日语的消息。

    我使用的是coffeescript、haml、scss,没有ERB

    因此,多语言消息在我的所有视图中都可以正常工作,但是,我添加了一个 .js 库,用于用带有下拉列表的漂亮组合框替换浏览器丑陋的下拉框,它使用哈希来保存本地语言中的消息。

    所以我做的是:

    _form.html.haml

    :coffeescript
      menssages_for_select2 [
        "#{I18n.t('select.formatNoMatches')}"
        "#{I18n.t('select.formatInputTooShort')}"
        "#{I18n.t('select.formatInputTooLong')}"
        "#{I18n.t('select.formatSelectionTooBig')}"
        "#{I18n.t('select.formatLoadMore')}"
        "#{I18n.t('select.formatSearching')}"
      ]
    

    我在视图中执行此操作,因此我可以访问 I18n 库。如果我尝试访问 .js.coffee 中的 I18n 库,则会失败

    现在,在

    mycode.js.coffee

    @mensajes_select2 = (txt) ->
      $.extend $.fn.select2.defaults,
        formatNoMatches: ->
          txt[0]
        formatInputTooShort: (input, min) ->
          txt[1]
        formatInputTooLong: (input, max) ->
          txt[2]
        formatSelectionTooBig: (limit) ->
          txt[3]
        formatLoadMore: (pageNumber) ->
          txt[4]
        formatSearching: ->
          txt[6]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      相关资源
      最近更新 更多