JavaScript Equivalent of Rails Try Method

Javascript equivalent of Rails try method

Optional Chaining Operator

Is a new proposal for ECMAScript.

It is in an early stage but we can start using it with babel.

This is the problem:

const person = {name: 'santiago'}
let zip = person.address.zip // Cannot read property 'zip' of undefined

This is how it works:

const person = {name: 'santiago'}
let zip = person?.address?.zip // undefined

To start using it we need babel alpha 7:

npm install --save-dev babel-cli@7.0.0-alpha.19
npm install --save-dev babel-plugin-transform-optional-chaining@^7.0.0-alpha.13.1

And we need to add the plugin to our .babelrc

{
"plugins": ["transform-optional-chaining"]
}

Adam Bene Medium Post which explains how to use it and another use cases

Equivalent of .try() for a hash to avoid undefined method errors on nil?

You forgot to put a . before the try:

@myvar = session[:comments].try(:[], @comment.id)

since [] is the name of the method when you do [@comment.id].

Rails has a try method for all objects. Is there a way to do something similar in Javascript?

var tryPath = function tryPath() {
if (arguments.length < 2) {
return undefined; // Not valid
} else {
var object = arguments[0];
for (var i = 1; i < arguments.length; i++) {
if (object !== null && typeof object === 'object') {
object = object[arguments[i]];
} else {
return undefined;
}
}
return object;
}
};

Execute ruby method within Javascript - Ruby on Rails App

It helps to know what you expect it to do and what it is actually doing.

The logs tell us there is an exception being raised: ActionView::MissingTemplate. The "Missing template users/increase_workouts, application/increase_workouts" message is telling you something important about a missing view template and it's giving you the locations where it expects to find a template.

When you talk to a controller action by sending a request, it needs to know how to respond to your request. By convention, Rails renders a template with the same name as the action, e.g. index.html.erb or index.jbuilder, but in the case of your special action, you either need to create a response template or tell the controller what to render.

Something like this right after you add one to the workouts in your controller action should give you a "success" response.


render(json: { message: "Workouts increased" }, status: :ok) and return

But you can also just render(status: :ok) and return. The :ok here is a human-friendly way of indicating the HTTP status code 200, which your client (the JS on your page) needs to see in a response.

For more details, see http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

Safe navigation equivalent to Rails try for hashes

&. is not equivalent to Rails' try, but you can use &. for hashes. Just use it, nothing special.

hash[:key1]&.[](:key2)&.[](:key3)

Although I would not do that.

Object doesn't support this property or method Rails Windows 64bit

Contrary to popular belief, Rails is NOT cross platform compatible as they claim. If it was it would work on windows, out of the box. Like you I have tried every available option.

This was solved using Ruby 2.1.5p273/Rails 4.2.0

I changed execjs to use UTF-8 with jscript, no effect. This was done by editing C:\RailsInstaller\Ruby2.1.0\lib\ruby\gems\2.1.0\gems\execjs-2.2.2\lib\execjs\runtimes.rb changing the JScript = block to the following.

JScript = ExternalRuntime.new(
name: "JScript",
command: "cscript //E:jscript //Nologo",
runner_path: ExecJS.root + "/support/jscript_runner.js",
encoding: 'UTF-8' # CScript with //U returns UTF-16LE
)

I also tried installing therubyracer which leads to problems with the libv8 dependency not compiling. I added my python 2.7 install to the windows system path, and installed libv8. Then it said libv8 was installed but when I tried to install therubyracer it said libv8 couldn't be found. I uninstalled libv8 and tried again and it said libv8 couldn't be compiled. That was enough for me to determine that therubyracer was not going to work on windows, so I commented it out of my Gemfile, leaving python 2.7 on my windows system path.

I updated coffee-script-source, by adding the following to my Gemfile

gem 'coffee-script-source', '1.9.0'

After adding coffee-script-source to my Gemfile I ran gem update coffee-script-source , this also didn't solve the problem.

I then installed node.js, this worked for 5 minutes until I generated a new controller, and it was broken again.

Note: After installing node.js you need to open a new command prompt to get the updates to your system path that are setup when node.js installs.

Finally what fixed this problem was to open up the app\assets\javascripts\application.js file and remove the last line which says

//= require_tree .

Lastly run the following command to make sure coffee-script is properly installed in Node.js

npm install -g coffee-script

method can? in javascript file

If spr_well_types.js.erb is in your assets pipeline (IE /app/assets/javascripts/...), you'll find that you can't use any of the object-orientated methods inside it.

As mentioned by Martin M, this is because assets are meant to be static (CSS/JS). They can be precompiled so that they have small file sizes (minified) in production.

Using paths and other helpers is acceptable (these won't change), but trying to use methods such as can? simply won't work (they rely on dynamic data).

The simple explanation is that JS is client-side whilst Rails is server-side. JS doesn't have access to the same data as Rails, and thus cannot run methods on non-existent data.


Views

If you wanted to use this type of functionality, you'd have to put it in your views directory, calling it through a controller action.

This server-side javascript is not precompiled, and does have access to the same data as Rails. Thus, with the help of ERB, you can use the object-orientated methods you require.

You've not given enough context for me to know how you're calling the file, but this is an example of what you can do:

#app/controllers/spr_well_types_controller.rb
class SprWellTypesController < ApplicationController
def show
# your code here
respond_to do |format|
format.js #-> app/views/spr_well_types/show.js.erb
end
end
end

#app/views/spr_well_types/show.js.erb
<% if can? :buttoncreate, SprWellType %>
container.append('<div style="margin-left: 5px; float: left;" id="spr_well_type_addrowbutton"><span class="glyphicon glyphicon-plus"></span>Add</div>');
<% end %>

It must be noted that respond_to takes the request mime type, meaning if you want to process both html and js responses, you'll have to send the different requests using their respective method. I can explain more about that if required.

Call Javascript from Rails 6 Service Object

You don't need to compile or transpile the Javascript if it's not running in the browser. You can send the data from Rails to Node by executing a shell script from Ruby.

In the Service Object (or Controller):

require "open3"
output, status = Open3.capture2("node ./lib/test.js", stdin_data: document)
# The `output` variable above will be returned with the content of `data` from the below script.
puts output

Script in /lib or /bin:

const fs = require('fs');

fs.readFile(0, 'utf8', function(err, data) {
if (err) throw err;
// do your proccessing here...
console.log(data);
});

how to call controller method from javascript in rails

On routes.rb, Please make the following change,

resources :jobs do
post :update_work_flow, on: :collection

In Js, you have specified as 'post' method, while in routes, you have specified a 'get' method. Try changing to post and the code should work.



Related Topics



Leave a reply



Submit