Jade equivalent of <%= %> - express

I'm trying to implement toastr notifications on my express application using express-toastr (https://github.com/kamaln7/express-toastr). The documentation says that after including the following in the controller:
if (err)
{
req.toastr.error('Invalid credentials.');
} else {
req.toastr.success('Successfully logged in.', "You're in!");
}
we have to include the libraries in the on the views. That is okay. But we also have to include something like this :
<%= req.toastr.render() %>
What is the equivalent of this on jade?
Thanks

Use:
div #{req.toastr.render()}
related post: https://www.filosophy.org/post/34/using_javascript_functions_within_the_jade_templating_language/

Related

How can I submit a form on input change with Turbo Streams?

I have a form I want to submit automatically whenever any input field is changed. I am using Turbo Streams, and if I use onchange: "this.form.submit()" it isn't captured by Turbo Streams and Rails uses a standard HTML response. It works fine when clicking the submit button. How can I work around this?
There is a discussion on the hotwire forum, where Mark Godwin figured out why form.submit() isn't working with turbo:
Turbo intercepts form submission events, but weirdly, the JS formElement.submit() method does not trigger the submit event.
And Jacob Daddario figures out that you can use form.requestSubmit() instead:
It turns out that the turbo-stream mechanism listens for form submission events, and for some reason the submit() function does not emit a form submission event. That means that it’ll bring back a normal HTML response. That said, it looks like there’s another method, requestSubmit() which does issue a submit event.
So you can change your code slightly, and use requestSubmit() if a browser supports it, and use submit() if not:
onchange: "this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()"
Update:
As BenKoshy pointed out, in Turbo 7.1.0, a polyfill was added so you can use form.requestSubmit() without checking for browser support, so you can add this to your input field:
onchange: "this.form.requestSubmit()"
I need to implement this for an app with lots of forms. I wound up using Stimulus. Below is the whole controller:
import { Controller } from "stimulus"
const _ = require("lodash")
export default class extends Controller {
connect() {
let that = this;
that.element.addEventListener('change', _.debounce(that.handleChange, 500))
}
handleChange(event) {
event.preventDefault()
// event.target.name // => "user[answer]"
// event.target.value // => <user input string>
event.target.form.requestSubmit()
}
}
and here it's used in a form with a single text input. NOTE the controller is attached to the form, not to the inputs.
<%= turbo_frame_tag dom_id(form_model) do %>
<%= form_with model: form_model,
format: :turbo_stream,
html: { data: { controller: "buttonless-form" } } do |f| %>
<%= f.hidden_field :question_id, value: question.id %>
<%= f.text_field :answer_value, class: "input shadow wide", placeholder: "Enter your answer here" %>
<% end %>
<div id=<%= "question_#{question.id}_output" %>>
<p> <!-- feedback to the user shows up here via Turbo -->
</div>
<% end %> <!-- end turbo frame -->

Pass -express-flash-messages- in an EJS file

I've a user controller which has a basic authentication logic. I'm using an ejs view engine . I'm finding trouble accessing these flash messages in my view, i.e. .ejs file. What should be the right approach. I dug through some information and found out that we can pass parameters during a res.redirect. However, I don't want to do that, since it will appear in the URL. Is there a solution to this, something like what pug engine has.
if (!user || !user.authenticate(req.body.password)) {
req.flash('error', 'Invalid email or password!')
res.redirect('/login')
return
}
You could pass your flash messages to your views using res.locals object:
app.get('/login', function(req, res) {
res.render('login', { errorMessage: req.flash('error')[0] });
});
Then in your view:
<% if (errorMessage) { %>
<div class="error">
<p><%= errorMessage %></p> <!-- Invalid email or password! -->
</div>
<% } %>

Tracking of vehicles in Rails via geocoding and plotting on a map

I have a Rails 3.2.19 app that I'd like to track vehicles (Units) with using geocoding and plotting on Google Maps.
I came up with a way to get coordinates by using the taip_parser gem and creating a rake task that constantly listens for inbound taip data, parses the latitude and longitude and updates the vehicle model's latitude and longitude fields. From there I was able to plot vehicle locations using the gmaps4rails gem. The limitation of this is that you have to use a specific 3G/4G modem that speaks in TAIP to send the lat/long to the Rails server so the rake task can parse it.
What I'd like to do is to negate having to use these expensive 3G/4G modems and instead pull the coordinates from a mobile device located in the vehicle (currently an iPad).
So my thoughts are to use the HTML5 Geolocation feature in the browser to obtain the latitude and longitude of the unit and somehow store that into the Unit's latitude/longitude database fields upon page/partial refresh which happens currently via Ajax.
This would break the dependence on the the existing devices and allow any mobile GPS enabled device to be compatible with this feature.
Currently in my app I have gmaps4rails to plot the units using my rake task and taip data parsing and also geocoder which I'm testing to geocode addresses as they are created for another purpose.
My questions are:
Can someone provide an example of how to use the HTML5 geolocation feature in a rails view? Once HTML5 geolocation is enabled in the view, how to get the latitude and longitude into the respective models latitude and longitude fields? Perhaps an example iteration of multiple objects' latitude longitude using gmaps4rails
If my question is too vague or convoluted please let me know so I can edit it and make things more clear as to what I'm trying to do.
I was able to get this working by using some ajax and a custom controller action in my Rails app. Using Ajax and a hidden form, I pull the coordinates using HTML5, populate the form with the values, and to an ajax post submit.
See below for the code:
controller
def update_gps
#unit = current_user.unit
if #unit.update_attributes(params[:unit])
respond_to do |format|
format.html {redirect_to mdt_path}
format.js { render "index"}
end
end
end
index.html.erb
<div class="hidden">
<%= form_for(#unit, :url => update_gps_mdt_index_path, :html => {:method => :post}) do |f| %>
<%= f.text_field :latitude %>
<%= f.text_field :longitude %>
<%= f.button :submit %>
<% end %>
</div>
<script>
$(function() {
setInterval(function(){
$.getScript("/mdt");
}, 10000);
});
function updateCurrentLocation(){
navigator.geolocation.getCurrentPosition(function(position) {
var c = position.coords
var location = c.latitude +", "+ c.longitude
console.log(location)
var $updateLocationForm = $(".edit_unit")
$("#unit_latitude").val(c.latitude)
$("#unit_longitude").val( c.longitude)
var data = $(".edit_unit").serialize();
console.log(data)
$.ajax({
type: "POST",
url: $(".edit_unit").attr("action"),
data: data,
success: function(data) {
console.log('working: '+data);
},
error: function(msg) {
console.log('not working '+msg);
}
});
});
}
setInterval(updateCurrentLocation, 10000)
</script>

How to render js rails 3

I have a vote model with "like", "dislike" actions. I have a route for each of these actions. When I call the actions, I'm returning a json response. My problem is that first, I need to figure out how to send the query to my like/dislike actions. I need to access ruby/rails variables from my javascript (I'm sending an ajax request using jquery's $.getJSON), so that for example I can create the request for the correct item. Help much appreciated.
A popular technique is to attach data to the dom. For example (pseudocode follows):
<% items.each do |item| %>
<div class="like_button" data-item-id="<%= item.id %>">Like</div>
<% end %>
and in the JavaScript:
$(".like_button").on("click", function() {
var item_id = $(this).data('item-id'); // from the dom
// construct Ajax request for item_id
});

Rails 3, how to prevent ajax remote calls (jquery) with a link_to and :remote => true with JS

So I have a simple ajax call to a page:
= link_to 'click me', my_path, :onclick => "if ($('#go').val() == "ok") { alert('going'); } else { return false; }", :remote => true do
This works just fine, I see the alert only when my field with id "go" has ok in there... but the issue is that the remote action triggers every time no matter what.
If this was not a remote link it would work just fine, not going through with the link, but it does not seem to behave the same way with a :remote => true ?
How can I achieve the expected result ?
Thanks,
ALex
The issue here is that the Rails UJS driver will see the data-remote and then perform the action because of a function like this in rails.js so perhaps try setting the property om your link inside the JS and remove the :remote => true. That might work however I dont know if rails.js would bind to that correctly or not.
Also, consider placing this JS in the application.js once you're done debugging just so you dont have inline JS all over your controllers.