Skip to content

Commit

Permalink
Rework NIL module definition via RubyVariables.WRAPPER. #297
Browse files Browse the repository at this point in the history
  • Loading branch information
bogdan committed Feb 18, 2022
1 parent dba9abe commit a1e0b81
Show file tree
Hide file tree
Showing 10 changed files with 55 additions and 59 deletions.
1 change: 1 addition & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ There are several possible ways to setup JsRoutes:

* [Quick and easy](#quick-start)
* Uses Rack Middleware to automatically update routes locally
* Automatically generates routes files on `assets:precompile` in production
* Works great for a simple Rails application
* [Webpacker ERB Loader](#webpacker)
* Requires ESM module system (the default)
Expand Down
23 changes: 21 additions & 2 deletions lib/js_routes/instance.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,35 @@ def js_variables
'DEPRECATED_GLOBBING_BEHAVIOR' => ActionPack::VERSION::MAJOR == 4 && ActionPack::VERSION::MINOR == 0,

'APP_CLASS' => application.class.to_s,
'NAMESPACE' => json(@configuration.namespace),
'DEFAULT_URL_OPTIONS' => json(@configuration.default_url_options),
'PREFIX' => json(@configuration.prefix),
'SPECIAL_OPTIONS_KEY' => json(@configuration.special_options_key),
'SERIALIZER' => @configuration.serializer || json(nil),
'MODULE_TYPE' => json(@configuration.module_type),
'WRAPPER' => @configuration.esm? ? 'const __jsr = ' : '',
'WRAPPER' => wrapper_variable,
}
end

def wrapper_variable
case @configuration.module_type
when 'ESM'
'const __jsr = '
when 'NIL'
namespace = @configuration.namespace
if namespace
if namespace.include?('.')
"#{namespace} = "
else
"(typeof window !== 'undefined' ? window : this).#{namespace} = "
end
else
''
end
else
''
end
end

def application
@configuration.application
end
Expand Down
1 change: 0 additions & 1 deletion lib/routes.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ declare const RubyVariables: {
SPECIAL_OPTIONS_KEY: string;
DEFAULT_URL_OPTIONS: RouteParameters;
SERIALIZER: Serializer;
NAMESPACE: string;
ROUTES_OBJECT: RouteHelpers;
MODULE_TYPE: ModuleType;
WRAPPER: <T>(callback: T) => T;
Expand Down
26 changes: 5 additions & 21 deletions lib/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* File generated by js-routes RubyVariables.GEM_VERSION
* Based on Rails RubyVariables.RAILS_VERSION routes of RubyVariables.APP_CLASS
*/
RubyVariables.WRAPPER((that) => {
RubyVariables.WRAPPER(() => {
const hasProp = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
let NodeTypes;
(function (NodeTypes) {
Expand All @@ -15,7 +15,6 @@ RubyVariables.WRAPPER((that) => {
NodeTypes[NodeTypes["SLASH"] = 7] = "SLASH";
NodeTypes[NodeTypes["DOT"] = 8] = "DOT";
})(NodeTypes || (NodeTypes = {}));
const Root = that;
const isBroswer = typeof window !== "undefined";
const ModuleReferences = {
CJS: {
Expand Down Expand Up @@ -70,11 +69,11 @@ RubyVariables.WRAPPER((that) => {
},
},
NIL: {
define(routes) {
Utils.namespace(Root, RubyVariables.NAMESPACE, routes);
define() {
// Defined using RubyVariables.WRAPPER
},
isSupported() {
return !RubyVariables.NAMESPACE || !!Root;
return true;
},
},
DTS: {
Expand Down Expand Up @@ -445,21 +444,6 @@ RubyVariables.WRAPPER((that) => {
is_reserved_option(key) {
return ReservedOptions.includes(key);
}
namespace(object, namespace, routes) {
const parts = (namespace === null || namespace === void 0 ? void 0 : namespace.split(".")) || [];
if (parts.length === 0) {
return;
}
for (let index = 0; index < parts.length; index++) {
const part = parts[index];
if (index < parts.length - 1) {
object = object[part] || (object[part] = {});
}
else {
object[part] = routes;
}
}
}
configure(new_config) {
this.configuration = { ...this.configuration, ...new_config };
return this.configuration;
Expand Down Expand Up @@ -502,4 +486,4 @@ RubyVariables.WRAPPER((that) => {
};
Utils.define_module(RubyVariables.MODULE_TYPE, result);
return result;
})(this);
})();
31 changes: 5 additions & 26 deletions lib/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ declare const RubyVariables: {
SPECIAL_OPTIONS_KEY: string;
DEFAULT_URL_OPTIONS: RouteParameters;
SERIALIZER: Serializer;
NAMESPACE: string;
ROUTES_OBJECT: RouteHelpers;
MODULE_TYPE: ModuleType;
WRAPPER: <T>(callback: T) => T;
Expand All @@ -97,7 +96,7 @@ declare const define:
declare const module: { exports: any } | undefined;

RubyVariables.WRAPPER(
(that: unknown): RouterExposedMethods => {
(): RouterExposedMethods => {
const hasProp = (value: unknown, key: string) =>
Object.prototype.hasOwnProperty.call(value, key);
enum NodeTypes {
Expand Down Expand Up @@ -128,7 +127,6 @@ RubyVariables.WRAPPER(
[T in keyof RouteNodes]: RouteNode<T>;
}[keyof RouteNodes];

const Root = that;
const isBroswer = typeof window !== "undefined";
type ModuleDefinition = {
define: (routes: RouterExposedMethods) => void;
Expand Down Expand Up @@ -186,11 +184,11 @@ RubyVariables.WRAPPER(
},
},
NIL: {
define(routes) {
Utils.namespace(Root, RubyVariables.NAMESPACE, routes);
define() {
// Defined using RubyVariables.WRAPPER
},
isSupported() {
return !RubyVariables.NAMESPACE || !!Root;
return true;
},
},
DTS: {
Expand Down Expand Up @@ -660,25 +658,6 @@ RubyVariables.WRAPPER(
return ReservedOptions.includes(key as any);
}

namespace(
object: any,
namespace: string | null | undefined,
routes: unknown
): void {
const parts = namespace?.split(".") || [];
if (parts.length === 0) {
return;
}
for (let index = 0; index < parts.length; index++) {
const part = parts[index];
if (index < parts.length - 1) {
object = object[part] || (object[part] = {});
} else {
object[part] = routes;
}
}
}

configure(new_config: Partial<Configuration>): Configuration {
this.configuration = { ...this.configuration, ...new_config };
return this.configuration;
Expand Down Expand Up @@ -734,4 +713,4 @@ RubyVariables.WRAPPER(
Utils.define_module(RubyVariables.MODULE_TYPE, result);
return result;
}
)(this);
)();
1 change: 0 additions & 1 deletion spec/js_routes/module_types/dts/routes.spec.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ declare const RubyVariables: {
SPECIAL_OPTIONS_KEY: string;
DEFAULT_URL_OPTIONS: RouteParameters;
SERIALIZER: Serializer;
NAMESPACE: string;
ROUTES_OBJECT: RouteHelpers;
MODULE_TYPE: ModuleType;
WRAPPER: <T>(callback: T) => T;
Expand Down
1 change: 1 addition & 0 deletions spec/js_routes/module_types/nil_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
let(:_presetup) { "" }
before do
evaljs("var window = this;")
evaljs("window.PHM = {}")
evaljs(_presetup)
evaljs(generated_js)
end
Expand Down
9 changes: 6 additions & 3 deletions spec/js_routes/options_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -399,13 +399,16 @@
end

let(:_presetup) do
window = {location: {
location = {
protocol: current_protocol,
hostname: current_hostname,
port: current_port,
host: current_host,
}}
"const window = #{ActiveSupport::JSON.encode(window)}"
}
[
"const window = this;",
"window.location = #{ActiveSupport::JSON.encode(location)};",
].join("\n")
end

context "without specifying a default host" do
Expand Down
5 changes: 4 additions & 1 deletion spec/js_routes/rails_routes_compatibility_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

describe JsRoutes, "compatibility with Rails" do

let(:generated_js) do
JsRoutes.generate({module_type: nil, namespace: 'Routes'})
end
before(:each) do
evaljs(JsRoutes.generate({module_type: nil, namespace: 'Routes'}))
evaljs(generated_js)
end

it "should generate collection routing" do
Expand Down
16 changes: 12 additions & 4 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,14 @@ def js_error_class
def evaljs(string, force: false, filename: 'context.js')
jscontext(force).eval(string, filename: filename)
rescue MiniRacer::ParseError => e
message = e.message
_, _, line, _ = message.split(':')
code = line && string.split("\n")[line.to_i-1]
raise "#{message}. Code: #{code.strip}";
trace = e.message
_, _, line, _ = trace.split(':')
if line
code = string.split("\n")[line.to_i-1]
raise "#{trace}. Code: #{code.strip}";
else
raise e
end
rescue MiniRacer::RuntimeError => e
raise e
end
Expand All @@ -62,6 +66,10 @@ def planner_routes
Planner::Engine.routes.url_helpers
end

def log(string)
evaljs("console.log(#{string})")
end

ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular "budgie", "budgies"
end
Expand Down

0 comments on commit a1e0b81

Please sign in to comment.