Destroy data based on HTML class name in Rails - html

I'm building a simple todo list using Rails (3.2.5).
I show all of the users todo items in an unordered list, each list item being the todo itself. By clicking on the todo item the user marks it as completed. Using jQuery I give the li a class of done so I can change its styling. By clicking on a "Clear completed" button I want the completed items to be destroyed (and deleted from the database).
How can this be done?
NB: I'm basically trying to recreate this app using Rails: http://davidpdrsn.com/todos/

You can do it using a remote form
So you would have something like
you would have a form with remote: true for each item or you could have only one form and submit it with JQuery.
class TodoController
def set_completed
#todo = Todo.find(params[:id])
#todo.done = true # you could move this to your model and do something like #todo.done! and that would save it automatically
#todo.save
end
def destroy_completed
#todos_to_delete = Todo.where(done: true)# here you could also move it to your model and do it like Todo.completed
#todos_to_delete.destroy_all
end
end
and you would render the response with the js for formatting, or even removing items on your list, like
views/todo/set_completed.erb.js
$("#item_<%= #todo.id %>").addClass("completed");

Supposing the model is called Todo and the completed column is called completed, you can write one of these in the controller:
Todo.destroy_all(:completed => true)
Todo.where(:completed => true).destroy_all
If you need help with how to manage the ajax request/response, here there is a good start (sorry, I don't want to give you the solution, IMHO you should make your way by yourself)
Resources: ActiveRecord#Base::destroy_all

Related

How should I access generated children of a custom HTML component in an idiomatic React way?

I am attempting to create a search bar using a custom HTML component for predictive text input. The way this component is built, it generates several plain HTML children that I need to act on to get full features. Specifically, I need to execute a blur action on one of the generated elements when the user presses escape or enter.
I got it to work using a ref on the custom component and calling getElementsByClassName on the ref, but using getElementsByClassName does not seem like the best solution. It pierces through the virtual and has odd side effects when testing.
This is a snippet of the component being rendered:
<predictive-input id='header-search-bar-input' type='search'
value={this.state.keywords}
ref={(ref: any) => this.predictiveInput = ref}
onKeyDown={(e: React.KeyboardEvent<any>) => this.handleKeyDown(e)}>
</predictive-input>
and the keyDown handler:
private handleKeyDown(e: React.KeyboardEvent<any>) {
// must access the underlying input element of the kat-predictive-input
let input: HTMLElement = this.predictiveInput.getElementsByClassName('header-row-text value')[0] as HTMLElement;
if (e.key === 'Escape') {
// blur the predictive input when the user presses escape
input.blur();
} else if (e.key === 'Enter') {
// commit the search when user presses enter
input.blur();
// handles action of making actual search, using search bar contents
this.commitSearch();
}
}
The element renders two children, one for the bar itself and one for the predictive dropdown. The classes of the underlying in the first are 'header-row-text' and 'value', so the element is correctly selected, but I am worried that this is violating proper React style.
I am using React 16.2, so only callback refs are available. I would rather avoid upgrading, but if a 16.3+ solution is compelling enough, I could consider it.
If you don't have any control over the input then this is the best approach in my opinion.
It's not ideal, but as you're stuck with a 3rd party component you can only choose from the methods that are available to you. In this case, your only real options are to find the element based on its class, or its position in the hierarchy. Both might change if the package is updated, but if I had to choose which would be more stable, I'd go for className.

Flask: buttons with varying functions

I'm writing a program in flask. In one of the pages (/search), the user will have a field to enter a string and click a search button. The result page that follows works all right, which consists of an html page with several images on it.
Now i want to add a button next to each image that, once clicked, will add an item to my mongoDB database.
So, 2 problems:
1) The buttons i managed to create so far will demand a "return redirect(page)". I don't want that. The user must be allowed to click several buttons in sequence, instead of having to perform a new search.
2) i built my own mechanism for rendering the result.html page. According to the search results, my code opens result.html and writes (appends) the urls on it.
#app.route('/add', methods = ['POST'])
def add():
print "hi"
return None ##Python won't accept 'return None' here =(
[...]
w=open("result.html", "a")
[...]
for k in cursor:
try:
w.write(k['url'] + "'> <form action='/add' method='post'> \
<input type='submit' value='Add'></input></form>")
How can i make the button tell the /add view function know the url for each image? I suppose there is something i should replace in this last block of code.

How do I implement specific interface methods using closure conversion in jruby?

I would like to take different actions when an swt menu is shown or hidden, so I am adding a MenuListener to a Menu
If I create the listener using a class and add an instance of that class via add_menu_listener I can separately detect showing events and hiding events. For example using the following Listener class:
class MyListener
include MenuListener
def menu_shown e
puts "#{e} was a show event"
end
def menu_hidden e
puts "#{e} was a Hide event"
end
end
and then add the listener to the menu via
my_menu.add_menu_listener MyListener.new
will print different messages when the menu is shown vs hidden.
I can also add a listener using "closure conversion" for example this will produce a message whenever the menu is shown or hidden.
my_menu.add_menu_listener { |e| puts "#{e} was a menu event" }
These two sections of the jruby wiki seem to cover implementing interfaces in jruby.
https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby#implementing-java-interfaces-in-jruby
https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby#closure-conversion
The second section seems to indicate that this "closure conversion" method should work for any interface, but I can't figure out out to get it to separate out the two different methods.
Does anyone know how to use this "closure conversion" scheme to implement each of the specific interface methods separately?
Looking more closely at https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby#closure-conversion
I see this statement:
The block is converted to a Proc object, which is then decorated with
a java interface proxy that invokes the block for any method
called on the interface.
I think this means there is no way to tell what method called the block.
What I decided to (unless someone has a better solution) is this
show = "Show"
hide = "Hide"
my_listener = MenuListener.new
my_listener.define_singleton_method(:menu_shown) { |e| puts "#{e} was a #{show} event" }
my_listener.define_singleton_method(:menu_hidden) { |e| puts "#{e} was a #{hide} event" }
my_menu.add_menu_listener my_listener
Note:
I chose this over
my_listener = MenuListener.new
class << my_listener
def menu_shown e
...
end
def menu_hidden e
...
end
end
my_menu.add_menu_listener my_listener
since I need to reference some free variables as shown above

Custom Register form not working

Hie folks..... When I click on submit button of the CUSTOM REGISTRATION form..... it redirects to the same page...... ?? No idea what this is about......
Controller: default.py
def register():
form=auth.register()
form.add_button('Cancel', URL('register'))
return dict(form=form)
View: register.html
Please take the little pain to open this link to view the html file.... I am unable to post the exact html code in here... problem with syntax..
http://pastebin.com/bPQu2DX3
print form.errors -> Storage {}
print form.accepts(request.vars,session) -> false
You have duplicated line form=auth.register()
You return dict(late=late, form=form) but late is never used in your controller...
I think you should simplify your controller :
def register():
form=auth.register()
form.add_button('Cancel', URL('register'))
return dict(form=form)
First, your first two lines are useless, as the third line simply overwrites the "form" variable with a completely new object. Second, auth.register() already handles the form processing, so you cannot subsequently call form.accepts(). If you want to control the flash messages, use the auth.messages object to set them.
Thanx folks .. Finally got the answer....
I was not putting all the fields in custom form..
the fields that one doesn't require and is validated as not null also needs to be mentioned in custom form as hidden attributes otherwise whole of the form won't get accepted.

How to use a QGraphicsWebView?

I want to use a QGraphicWebView inside a delegate to render a QTableView cell, but I just don't know what to do with the QStyleOptionGraphicsItem parameter the paint() method requires. How to build it up / where should I retrieve it?
I'm using this code as reference, so the paint() method should be something like this:
def paint(self, painter, option, index):
web = QGraphicsWebView()
web.setHtml(some_html_text)
web.page().viewportSize().setWidth(option.rect.width())
painter.save()
painter.translate(option.rect.topLeft());
painter.setClipRect(option.rect.translated(-option.rect.topLeft()))
web.paint(painter, ??????) # what here?
painter.restore()
Any advice?
I'll assume that you don't really need QGraphicsWebView and that QWebView is sufficient.
It's important to keep in mind that you're not expected to call QWidget::paintEvent() yourself. Given that constraint, you'll want to use a helper class that can render on a paint device or render using a given painter. QWebFrame has one such method in the form of its render function. Based off of your linked-to example, the following should work:
class HTMLDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
model = index.model()
record = model.listdata[index.row()]
# don't instantiate every time, so move this out
# to the class level
web = QWebView()
web.setHtml(record)
web.page().viewportSize().setWidth(option.rect.width())
painter.save()
painter.translate(option.rect.topLeft());
painter.setClipRect(option.rect.translated(-option.rect.topLeft()))
web.page().mainFrame().render(painter)
painter.restore()