How to set :autoclose option in Haml - ruby

I am actually generating some xml from haml template, using Padrino Framework.
There are some tags that are self closing.
For that I did add following statement in subapp/app.rb as padrino is based on sinatra
set :haml, :autoclose => %w[meta img link br hr input area param col base else var assign script log submit exit reprompt goto]
But the Result is same for
1. else tag
I get
<else> </else>
but expected is
<else />
Similar to br tag.

Try with in config/boot.rb
require 'haml/template/options'
Haml::Template.options[:autoclose] = %w[meta img link br hr input area param col base else var assign script log submit exit reprompt goto]

It has to be like this, if you're outside of Rails:
require 'haml/template/options'
Haml::Options.defaults[:format] = :xhtml

Related

Using Mechanize to log into https://kindle.amazon.com/login

I am trying to use Mechanize to log into my Kindle account at Amazon.
The login page URL is https://kindle.amazon.com/login
I can manually log into this page without issue but if I try it using the following code it always fails with an error (see screenshot below).
require 'mechanize'
mechanize_agent = Mechanize.new
mechanize_agent.user_agent_alias = 'Windows Mozilla'
signin_page = mechanize_agent.get("https://kindle.amazon.com/login")
signin_form = signin_page.form("signIn")
signin_form.email = "email#example.com"
signin_form.password = "password"
post_signin_page = mechanize_agent.submit(signin_form)
This is always the resulting page (again, I'm certain my script is using valid values):
Looks like mechanize is trying to submit the form without the propper action. Try using the Continue button, and send the form with that button:
# ...
submit_button = signin_form.buttons.find { |b| b.value == "Continue" }
post_signin_page = mechanize_agent.submit signin_form, submit_button

Mechanize form submission

I have a website that I am attempting to scrape using Mechanize.
When I submit the form, the form is submitted with an URL of the following format :
https://www.website.com/Login/Options?returnURL=some_form_options
(If I enter that URL in the browser, it will send me to a nice error page saying that the requested page does not exist)
Whereas, if I submit the form from the website, the returned URL will be of the following format :
https://www.website.com/topic/country/list_of_form_options
The website has a login form that is not necessary to fill in to be able to submit a search query.
Any idea why I would get a different URL submitting the same form with Mechanize ? And how to counter that ?
I cannot process the URL I get after "mechanizing" the form.
Thanks!
You can find the exact form that you want to submit then submit, If you are unable to find the path then Even you can add form field using Mechanize and submit that form. Here is my code that i have used in my project.
I had create a rake task for this task:
namespace :test_namespace do
task :mytask => [:environment] do
site = "http://www.website.com/search/search.aspx?term=search term"
# prepare user agent
ua = Mechanize.new
page = ua.get("#{site}")
while (true)
page.search("//div[#class='resultsNoBackground']").each do |res|
puts res.at("table").at('tr').at('td').text
link_text =res.at_css('strong').at('a').text
link_href = res.at_css('strong').at('a')['href']
link_href ="http://www.website.com"+link_href
page_content=''
res.css('span').each do |ss|
ss.css('strong').remove
page_content=ss.text.gsub(/Vi.*s\)/, '')
end
# puts "HERE IS THE SUMMMER ......#{content_summery}"
end
if page.search("#ctl00_ContentPlaceHolder1_ctrlResults_gvResults_ctl01_lbNext").count > 0
form = page.forms.first
form.add_field! "__EVENTTARGET", "ctl00$ContentPlaceHolder1$ctrlResults$gvResults$ctl01$lbNext"
form.add_field! "__EVENTARGUMENT", ""
page = form.submit
else
break
end
end
end
end

Sinatra query parameters

Trying to get familiar with sample Sinatra app for the Instagram Ruby gem. The issue is that I can't find the correct way to apply arguments to queries, for example I'm trying to set the amount of posts being shown to 30:
get "/user_recent_media" do
client = Instagram.client(:access_token => session[:access_token])
user = client.user
html =
"""
<h1 align=\"center\">#{user.username}</h1>
"""
for media_item in client.user_recent_media(self, options = {:count => 30})
html << "<img src='#{media_item.images.low_resolution.url}'>"
end
html
end
I tried to apply the parameters this way but it doesn't seem to be working.

Ruby-mp3info album artwork

I have this gem working such that I can change the id3 data for a given song. However I need to also be able to add album artwork to the song. I have the artwork at a given URL. How do I go about this?
Mp3Info.open(file.path) do |mp3|
mp3.tag.title = title
mp3.tag.artist = artist
end
It seems ruby-mp3info only supports text frames at the moment, see here: https://github.com/moumar/ruby-mp3info/blob/v0.7.1/lib/mp3info/id3v2.rb#L319
Using taglib-ruby, it would work like this:
require 'taglib'
require 'open-uri'
picture_data = open(picture_url).read
TagLib::MPEG::File.open(file.path) do |file|
tag = file.id3v2_tag
pic = TagLib::ID3v2::AttachedPictureFrame.new
pic.picture = picture_data
pic.mime_type = "image/jpeg"
pic.type = TagLib::ID3v2::AttachedPictureFrame::FrontCover
tag.add_frame(pic)
file.save
end
If you are not stuck with mp3Info gem, try using id3Lib, http://id3lib-ruby.rubyforge.org/. From my experience, that one's better.
not sure about this, but try reading the file and setting it directly to
mp3.tag2.APIC
Using ruby-mp3info you can add artwork:
From the documentation:
file = File.new('input_img','rb')
Mp3Info.open '1.mp3' do |m|
m.tag2.add_picture(file.read)
end

How can I measure the length of a long string in Ruby? SciTE and command prompt aren't working.

I've written a program that measures my typing speed. As part of this, I need it to count how many characters I've typed. I did that with
text = gets.chomp
puts text.length.to_s
Unfortunately, I can't get this working for a long string.
In the SciTE editor, .length doesn't work properly, so instead of giving me the length of the string, it gives me the character count of everything I've typed, including corrected mistakes - if I typo "Hrello" and correct it to "Hello", it'll still return 6 instead of 5.
I googled this, and the suggested fix was to run the program from the command prompt instead. In the command prompt, .length works fine, but it turned out that I can't type in more than 264 characters.
So I tried to put a GUI on the program with Shoes:
Shoes.app :width => 300, :height => 300 do
button "Start." do
text = ask "Type here."
para text.length.to_s
end
end
and discovered that Shoes' input box has an even shorter character limit.
I'm running Windows 7, Ruby 1.9.2, SciTe version 2.29 and Shoes Policeman Revision 1514.
How can I run this program so it'll correctly measure the length of a really long string? I'd be happy with any solution that fixes the command prompt or Shoes character limit, the SciTE bug, or just a suggestion for a different way to execute ruby programs where this will work.
I'd be happy with [...] a suggestion for a different way to execute ruby programs where this will work.
What about a simple web app? Here is a simple Sinatra app that accomplishes exactly what you have asked with a very large character limit.
require 'sinatra'
get '/' do
%{<html>
<body>
<form method="post">
<textarea name="typed"></textarea>
<input type="submit">
</form>
</body>
</html>
}
end
post '/' do
"You typed #{params['typed'].length} characters."
end
To run the app you can use something as simple as ruby sinatra_example.rb to use a built-in web server. Or, you can deploy this app using any of several web servers.
If you need timers this should be easy to accomplish through javascript and include in the form submit.
Ok, your question is not accurately titled, but lets see:
There is a very broad number of options of using command prompt, and you should consider running a simple script in ruby on it.
On command line from windows, try typing ruby C:/path_to_folder_program/program.rb
If it won`t execute, you can find on ruby folder some executable called ruby and should, from command prompt on that path, run it like above.
But let me ask you, why ruby? Other more accessible and user-friendly programming languages, like javascript would behave better and would be easier to make your program accessible.
- EDIT -
Seems shoes can handle more chars, use edit_box instead of ask:
In Shoes:
Shoes.app do
#txt = edit_box
button("How many"){ alert(#txt.text.size) }
end
Anyway, before trying shoes I did the exercise with that I knew, here it is:
In javascript:
<script>
function start_stop(){
var txt = document.getElementById('txt');
var btn = document.getElementById('btn');
if( txt.disabled ){
txt.value = '';
txt.disabled = false;
btn.value = 'Stop';
txt.focus();
startTime = new Date().getSeconds();
} else {
txt.disabled = true;
btn.value = 'Start again';
timeNow = new Date().getSeconds();
alert(txt.value.length + " characters in " + (timeNow - startTime) + " seconds.");
}
}
</script>
<input type='button' id='btn' onclick='start_stop()' value='Start'>
<textarea id='txt' rows='8' cols='80' disabled></textarea>
In Ruby using Qt: (replicating the same idea as in the javascript one)
require 'Qt'
class MyWidget < Qt::Widget
slots :start_stop
def initialize
super
setFixedSize(400, 120)
#btn = Qt::PushButton.new("Start")
#txt = Qt::TextEdit.new ; #txt.readOnly = true
vbox = Qt::VBoxLayout.new
vbox.addWidget #btn
vbox.addWidget #txt
setLayout vbox
connect(#btn, SIGNAL("clicked()"), self, SLOT(:start_stop))
end
def start_stop
if #txt.readOnly
#txt.plainText = ''
#txt.readOnly = false
#btn.text = "Stop"
#txt.setFocus
#startTime = Time.now
else
#txt.readOnly = true
#btn.text = "Start again (#{#txt.plainText.size} chars #{(Time.now - #startTime).to_i} in seconds)"
end
end
end
app = Qt::Application.new(ARGV)
widget = MyWidget.new
widget.show
app.exec

Resources