Using a user defined variable within a function? (Ruby, Watir) - ruby

I'm creating drag and drop feature that depends on upon ID for placement, it works perfectly fine, but I need the status of task to be user defined so the user will have control of where something will be dragged as each section is uniquely named.
getID refers to getting the reference id of a Div.
I'd then concatenating with a "_" as well as adding the user set word
Class:
def addtask
dropTask = #browser.div(:id => getID+"_"+"##{statusOfTask}")
dragTask = #browser.div(:id, "footer").span(:class, "headerDrag")
dragTask.drag_and_drop_on dropTask
end
User Script:
statusOfTask = ["Ready"]
addtask()
Any ideas?

You just need to pass the desired status text to the addTask() method.
Class (add statusOfTask as a parameter):
def addtask(statusOfTask)
dropTask = #browser.div(:id => getID+"_"+"##{statusOfTask}")
dragTask = #browser.div(:id, "footer").span(:class, "headerDrag")
dragTask.drag_and_drop_on dropTask
end
User Script (pass in the first (or desired) value of statusOfTask):
statusOfTask = ["Ready"]
addtask(statusOfTask[0])

Related

rails string substitution or similar solution in controller

I'm building a site with users in all 50 states. We need to display information for each user that is specific to their situation, e.g., the number of events they completed in that state. Each state's view (a partial) displays state-specific information and, therefore, relies upon state-specific calculations in a state-specific model. We'd like to do something similar to this:
##{user.state} = #{user.state.capitalize}.new(current_user)
in the users_controller instead of
#illinois = Illinois.new(current_user) if (#user.state == 'illinois')
.... [and the remaining 49 states]
#wisconsin = Wisconsin.new(current_user) if (#user.state == 'wisconsin')
to trigger the Illinois.rb model and, in turn, drive the view defined in the users_controller by
def user_state_view
#user = current_user
#events = Event.all
#illinois = Illinois.new(current_user) if (#user.state == 'illinois')
end
I'm struggling to find a better way to do this / refactor it. Thanks!
I would avoid dynamically defining instance variables if you can help it. It can be done with instance_variable_set but it's unnecessary. There's no reason you need to define the variable as #illinois instead of just #user_state or something like that. Here is one way to do it.
First make a static list of states:
def states
%{wisconsin arkansas new_york etc}
end
then make a dictionary which maps those states to their classes:
def state_classes
states.reduce({}) do |memo, state|
memo[state] = state.camelize.constantize
memo
end
end
# = { 'illinois' => Illinois, 'wisconsin' => Wisconsin, 'new_york' => NewYork, etc }
It's important that you hard-code a list of state identifiers somewhere, because it's not a good practice to pass arbitrary values to contantize.
Then instantiating the correct class is a breeze:
#user_state = state_classes[#user.state].new(current_user)
there are definitely other ways to do this (for example, it could be added on the model layer instead)

get text with index number and then compare with the expected text

I need to write a method which will get text with the help of index number from popup and then i need to compare with the expected text
i.e i need to verify expected plan name is displayed at the bottom of the popup box
Setting the correct id for the query (which you can get by doing on calabash console the command query("*", :id)) on code below should do the trick. If you can't use id try to get another component property (like Android component by using query("*") ) and set the query inside theget_text calls.
def get_text(query)
query(plan_query, :text).first
end
def text_equals(text, expected_text)
unless text == expected_text
fail "#{text} not equal to #{expected_text}"
end
end
def verify_plan(index, expected_text)
plan_text = get_text("* id:'PLAN_TEXTS_ID' index:#{index}") # Can change 'id:...'' by Android class if plan does not have id
expected_text = get_text("* id:'BOTTOM_PLAN_ID'") # Same as above
text_equals(plan_text, expected_text)
end

Getting model value and generated ID from within simple_form custom input

I'm trying to make a custom input type with simple_form that will implement combobox-type functionality using jQuery-Autocomplete
. What I need to do is output a hidden field that will hold the ID of the value selected and a text field for the user to type in.
Here's what I have so far:
class ComboboxInput < SimpleForm::Inputs::Base
def input
html = #builder.hidden_field(attribute_name, input_html_options)
id = '' #what?
value = '' #what?
return "#{html}<input class='combobox-entry' data-id-input='#{id}' value='#{value}'".html_safe
end
end
I need to get the ID of the hidden field that simple_form is generating to place as an HTML attribute on the text entry to allow the JavaScript to "hook up" the two fields. I also need to get the value from the model to prepopulate the text input. How do I do this from within my custom input?
I'm looking for the id as well, but I did get the value:
def input
current_value = object.send("#{attribute_name}")
end
I just found a hokey id workaround:
html = #builder.hidden_field(attribute_name, input_html_options)
id = html.scan(/id="([^"]*)"/).first.first.to_s
I know it's a hack, but it does work. Since we don't have access directly to this type of resolution, it is likely to keep working even if the underlying id creation code changes.

Why does ::TableView.model return nilClass when Nokogiri is used?

EDIT
The problem was with something else so the trouble wasn't really Qt, still I don't know why this happened.
The thing was that in the method display_filesize #yt.get_filesize(row_id, format) I used Nokogiri to parse the XML. I don't know if the XML was corrupted (it was loaded from quvi), but it was definitely the culprit. After switching to XMLSimple everything works fine.
The code I used:
def get_filesize(video_id, format)
video = #videos[video_id]
if video.formats[format].empty?
to_parse = `quvi --xml --format #{format} #{video.player_url}`
parsed = Nokogiri.parse(to_parse)
video.formats[format] = { :size => parsed.at('length_bytes').text,
:url => parsed.at('link').at('url').text }
end
video.formats[format][:size]
end
Now I use something like this:
def get_filesize(video_id, format)
video = #videos[video_id]
if video.formats[format].empty?
to_parse = `quvi --xml --format #{format} #{video.player_url}`
parsed = XmlSimple.xml_in(to_parse, {'KeyAttr' => 'name'})
video.formats[format] = { :size => parsed['link'][0]['length_bytes'][0],
:url => URI.decode(parsed['link'][0]['url'][0]) }
end
video.formats[format][:size]
end
It works beautifully. Still, I don't know why it crashed. This is the real question.
OLD QUESTION
I have a Qt::TableView that contains Qt::StandardItemModel. A row in the model consists of text, Qt::PushButton, checkbox and Qt::ComboBox. It works like this:
The user is presented with text values and can explore further if they want to.
The user clicks Qt::PushButton and the next cell is populated with a Qt::ComboBox containing other possible values to choose from.
If the user chooses an option from Qt::ComboBox, magic happens, objects get created, hashes populated and the cell on the right gets populated with appropriate text (through a Qt::StandardItem)
Then the checkbox can be checked.
After selecting the rows the user wants, a Qt::PushButton located outside of the Qt::TableView can be clicked. It then iterates through the model, tests if the checkbox is selected and should it be, tries to access the value in the appropriate ComboBox.
The problem is, when I insert code that tries to access the Qt::ComboBox, I can't insert the Qt::StandardItem, because I can't get the model, because Qt::TableView.model returns NilClass (at some point).
I don't know why and how this happens. It's a random thing, sometimes the value of Qt::ComboBox can be changed a couple times, sometimes the first try ends with an error.
Here is how I create the Qt::StandardItem:
def display_filesize
row_id = row_id_from_object_name(sender.objectName)
format = sender.currentText
filesize = #yt.get_filesize(row_id, format) # get the text
filesize_item = Qt::StandardItem.new("#{(filesize.to_i/1024/1024)} MB ")
# #tc simply stores the indexes of columns so I can access them easily
#ui.tableView.model.setItem(row_id, #tc[:filesize], filesize_item)
end
And here is how I try to access the Qt::ComboBox value:
model = #ui.tableView.model
checked = model.rowCount.times.map do |i|
if model.item(i, #tc[:check]).checkState == Qt::Checked
# if I remove the following two lines it works...
index = model.index(i, #tc[:formats])
format = #ui.tableView.indexWidget(index).currentText
#yt.videos[i][format]
end
end
And this is the error I am trying to get rid of:
searcher.rb:86:in `display_filesize': undefined method `index' for nil:NilClass (NoMethodError)
from /var/lib/gems/1.9.1/gems/qtbindings-4.8.3.0/lib/Qt/qtruby4.rb:469:in `qt_metacall'
from /var/lib/gems/1.9.1/gems/qtbindings-4.8.3.0/lib/Qt/qtruby4.rb:469:in `method_missing'
from /var/lib/gems/1.9.1/gems/qtbindings-4.8.3.0/lib/Qt/qtruby4.rb:469:in `exec'
from qutub-player.rb:17:in `<main>'

How to create XML object from string using xml-mapping in Ruby

I'm using xml-mapping in Ruby (on Sinatra) for some XML stuff. Generally I follow this tutorial: http://xml-mapping.rubyforge.org/. I can create objects and write them to XML strings using
login.save_to_xml.to_s
But when I try
login = Login.load_from_xml(xml_string)
I get the following error:
XML::MappingError - no value, and no default value: Attribute username not set (XXPathError: path not found: username):
Here is the XML string I receive:
<login><username>ali</username><password>baba</password></login>
This is what the class looks like:
class Login
include XML::Mapping
text_node :username, "username"
text_node :password, "password"
end
So the class name is the same, the nodes are named the same. I actually get the exact same string when I create an instance of my object and fill it with ali/baba:
test = Login.new
test.username = "ali"
test.password = "baba"
p test.save_to_xml.to_s
<login><username>ali</username><password>baba</password></login>
What am I missing?
Thanks,
MrB
EDIT:
When I do
test = login.save_to_xml
And then
login = Login.load_from_xml(test)
it works. So the problem seems to be that I'm passing a string, while the method is expecting.. well, something else. There is definitely a load_from_xml(string) method in the rubydocs, so not sure what to pass here. I guess I need some kind of reverse to_s?
It looks like you save_to_xml creates a REXML::Element. Since that works, you may want to try:
Login.load_from_xml(REXML::Document.new(xml_string).root)
See the section on "choice_node" for a more detailed example http://xml-mapping.rubyforge.org/

Resources