DRY从Rails设置document.domain的方式 [英] DRY way for setting document.domain from Rails

查看:444
本文介绍了DRY从Rails设置document.domain的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails应用程序,它使用两个子域,希望在JavaScript中沟通。什么是最干燥的方式来有效地设置 document.domain = mydomain.com

I have a Rails app that is using two subdomains which would like to communicate in JavaScript. What would be the most DRY way to effectively set document.domain = mydomain.com?


  1. 这不应该是开发或测试环境中的一个问题,其中域 localhost

  2. 这也需要在不加载主JavaScript文件的某些网页上设置

条件 1 让我想到我要么依赖一个正则表达式解析根域从位置.host 或在 erb 中切换。

Condition 1 leads me to think I either want to rely on a Regex that parses the root domain out of location.host or do the switching in erb.

条件 2 让我觉得最好写一次,把它放在资产管道中,并在必要时加入。

Condition 2 makes me feel it would be best to write this once and put it in the asset pipeline and include it where necessary.

创建 domain_setter.js.erb (下面的内容),将其添加到预编译列表,包括在所有必要的地方( \\ = require domain_setter 在清单中或 javascript_include_tag'domain_setter'没有清单)。

Create a file like domain_setter.js.erb (contents below), add it to precompile list, and include it in all necessary places (either \\= require domain_setter in manifests or javascript_include_tag 'domain_setter' for pages without manifests).

<%- if Rails.env.production? %>
  document.domain = 'mydomain.com';
<%- end %>



更新当前解决方案



更动态,不需要对域进行硬编码。仍然不是最好的,但它工作... 主要是: - /

(function() {
  var domain = /^(?:https?\:\/\/)?.*?([^.]+\.[^.]+?)(?:\:\d+)?$/.exec(location.host);

  if (domain == null) {
    document.domain = 'localhost';
  } else {
    document.domain = domain[1];
  }
})();



tl; dr



如何设置多个页面 document.domain 使用Rails?

推荐答案

我想你正在寻找跨源资源共享(CORS)。这允许javascript在不同的域之间进行AJAX $。get / post 请求。

I think you're looking for Cross-Origin Resource Sharing (CORS). This allows javascript to make AJAX $.get/post requests across different domains.

您开始: https://github.com/cyu/rack-cors#rails

您需要将 originins 属性设置为 yoursubdomain.herokuapp.com

这篇关于DRY从Rails设置document.domain的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆