how to search a particular string in rails? - ruby-on-rails

I have out put like below and i want to search for a particular string and it's value how to do this in rails.
ex : i want search for Nokogiri::XML::Text pattern and get all pattern matching Nokogiri::XML::Text
#<LinkedIn::Location:0x4a339e8 #doc=#<Nokogiri::XML::Document:0x2519cb8 name="document" children=[#<Nokogiri::XML::Element:0x2519a0c name="per
son" children=[#<Nokogiri::XML::Text:0x25197f0 "\n ">, #<Nokogiri::XML::Element:0x251970c name="`" children=[#<Nokogiri::XML::Text:0x2
519124 "\n ">, #<Nokogiri::XML::Element:0x25190f4 name="name" children=[#<Nokogiri::XML::Text:0x2518bd8 "Bengaluru Area, India">]>, #<Nokog
iri::XML::Text:0x2518b00 "\n ">, #<Nokogiri::XML::Element:0x2518ad0 name="country" children=[#<Nokogiri::XML::Text:0x2518680 "\n ">, #
<Nokogiri::XML::Element:0x2518650 name="code" children=[#<Nokogiri::XML::Text:0x2517fcc "in">]>, #<Nokogiri::XML::Text:0x2517eb8 "\n ">]>,
#<Nokogiri::XML::Text:0x2517cd8 "\n ">]>, #<Nokogiri::XML::Text:0x2517bdc "\n">]>]>>

You can get the value like :
Way-1 :
reader = Nokogiri::XML::Reader(xml)
reader.read #Moves to next node in document
reader.attribute("cdn") # To get the value of attributes
Way-2 :
doc = Nokogiri::XML(xml)
elems = doc.xpath("//*[#messageId]") #get all elements with an attribute of 'messageId'
elems[0].attr('messageId') #gets value of attribute of first elem

Related

Pattern matching with tag in Lua

I'm trying to parse a text, and based on tags to do actions.
The text is:
<window>
<caption>My window
</window>
<panel>
<label>
<caption>
<position>50,50
<color>255,255,255
</label>
</panel>
Code:
function parse_tag(chunck)
for start_tag,tag_name in string.gfind(chunck,"(<(.-)>)") do
if (child_obj[tag_name]) then
print(start_tag)
for data,end_tag in string.gfind(chunck,"<" .. tag_name ..">(.-)(</" .. tag_name ..">)") do
for object_prop,value in string.gfind(data,"<(.-)>(.-)") do
print("setting property = \"" .. object_prop .. "\", value of" .. value);
end
end
print("</" .. tag_name ..">");
elseif(findInArray(main_obj,tag_name)) then
print("Invalid data");
stop();
end
end
end
for key,tag in ipairs(main_obj) do
for start_tag,tag_name,chunck,end_tag in string.gfind(data,"(<(" .. tag.name .. ")>)(.-)(</" .. tag.name .. ">)") do --> searching for window/panel start and end tags
if (findInArray(main_obj,tag_name)) then
print(start_tag)
parse_tag(chunck); --> parses the tag with child tag
print(end_tag)
end
end
end
It seems to fail getting the value, as I get the following output:
<window>
</window>
<panel>
<label>
setting property = "caption", value of
setting property = "position", value of
setting property = "color", value of
</label>
</panel>
How can I use match the string after the first <%tag%> until the next <%tag%> or end of the chunk.
string.gfind(data,"<(.-)>(.-)")
Here, you try to match the value with .-. However, - is lazy, i.e, .- will try to match as little as possible, in this case, an empty string.
Try telling it to match until the next <:
string.gfind(data,"<(.-)>(._)<")
Tried different type of captures.
This
string.gfind(data,"<(.-)>([^%<+.-%>+]+)")
Seems to work

Print to a file using a variable as SQL active record column name?

Here is my psudocode example:
Mydb.find_by_sql("...").each do |data|
.
.
aFile.print(data.time.to_f, " ", data.column_name, "\n")
My question is how can I use a variable for the column_name? I thought something like:
aFile.print(data.time.to_f, " ", data.#{column_name}, "\n")
or
aFile.print(data.time.to_f, " ", data.'#{column_name}', "\n")
or
aFile.print(data.time.to_f, " ", data."#{column_name}", "\n")
but these didn't work.
Any ideas?
You could try
data.send('column_name')
So if the ActiveRecord returned has an attribute 'foo'
puts(data.foo)
is the same as
puts(data.send('foo'))
UPDATE RE your comment.
#x = X.find(1)
['date','age','sex'].each do |attr|
puts "The value of #{attr} is #{#x.send(attr)}"
end

Parsing with Ruby Mechanize

Im trying to parse a website using the Mechanize Gem. So far this is what I have:
page = agent.get("http://www.greatgiftsformen.com/price-range-under-c-131_142.html?page=all")
page.parser.xpath('//tr[(((count(preceding-sibling::*) + 1) = 2) and parent::*)]//*[contains(concat( " ", #class, " " ), concat( " ", "productListing-data", " " ))]')[5]
and I get the elements for this product back:
=> #<Nokogiri::XML::Element:0x81c175ec name="td" attributes=[#<Nokogiri::XML::Attr:0x81c17d58 name="valign" value="top">, #<Nokogiri::XML::Attr:0x81c17eac name="align" value="center">, #<Nokogiri::XML::Attr:0x81c17ec0 name="class" value="productListing-data">] children=[#<Nokogiri::XML::Element:0x805fa174 name="a" attributes=[#<Nokogiri::XML::Attr:0x81c13794 name="href" value="http://www.greatgiftsformen.com/gas-pump-retro-liquor-dispenser-p-249.html?osCsid=05f5dbb816874ece6db883c2c48d7ae1">] children=[#<Nokogiri::XML::Element:0x8068e270 name="img" attributes=[#<Nokogiri::XML::Attr:0x81c115ac name="src" value="product_thumb.php?img=images/prod/liquordisp-gas.jpg&w=160&h=160">, #<Nokogiri::XML::Attr:0x81c115c0 name="width" value="160">, #<Nokogiri::XML::Attr:0x81c115d4 name="height" value="160">, #<Nokogiri::XML::Attr:0x81c11714 name="border" value="0">, #<Nokogiri::XML::Attr:0x81c11728 name="alt" value="Gas Pump Retro Liquor Dispenser">, #<Nokogiri::XML::Attr:0x81c11750 name="title" value="Gas Pump Retro Liquor Dispenser">, #<Nokogiri::XML::Attr:0x81c11764 name="class" value="fotgal">]>]>]>
however when I try to get the href, I get back nil:
url = item.attributes['href']
=> nil
Needed to add the child nodes:
url = item.children[0].attributes['href'].to_s

Grails - Set "disabled" attribute name and value in GSP

I´m trying to do this without success:
<g:textField title="${title}" ${disabled} />
I want to apply a disabled attribute, ONLY if the ${disabled} variable is TRUE.
I don't want to use conditionals, because in other views I got a lot of code and using IF statements, will be a chaos.
The other thing is applying the attribute like this:
<g:textField title="${title}" disabled="${disabled}" />
But when I put the disabled attribute, no mather the content of the variable, It just always disables the field.
if you don't like gotomanners' solution (which seems perfectly valid to me)
<g:textField title="${title}" ${(disabled)?"disabled":""} />
your ${disabled} variable should be returning "disabled" not TRUE for that to work.
EDIT
I tried this out and saw the problem with it always being disabled no matter the value. Apparently the mere presence of the disabled keyword disables the field and the value assigned to that keyword is only a dummy value.
Anyway, Here's a fix.
Create a Taglib class(if you don't have one already)
define your own textfield tag as such...
def myTextField = { attrs, body ->
def title = attrs.remove("title")
def isDisabled = attrs.remove("disabled")
if ("true".equals(isDisabled)) {
out << """<input title="${title}" disabled="${isDisabled}" """
attrs.each { k,v ->
out << k << "=\"" << v << "\" "
}
out << "/>"
} else {
out << """<input title="${title}" """
attrs.each { k,v ->
out << k << "=\"" << v << "\" "
}
out << "/>"
}
}
in your gsp, call your textfield tag like so
<g:myTextField title="${title}" disabled="${disabled}" />
adding extra attributes like so is also valid
<g:myTextField class="title" name="theName" value="theValue" title="${title}" disabled="${disabled}" />
make sure your ${disabled} variable returns "true" or "false" as strings this time.

Replace white space with AND in ruby

I have someone entering a form with some string input. What I need to do is replace any white space in the string with " AND " (no quotes). What's the best way to do this?
Also, how would I go about doing this if I wanted to remove all the whitespace in the string?
Thanks
to replace with and:
s = 'this has some whitespace'
s.gsub! /\s+/, ' AND '
=> "this AND has AND some AND whitespace"
to remove altogether:
s = 'this has some whitespace'
s.gsub! /\s+/, ''
=> "thishassomewhitespace"
Split and join is another technique:
s = " a b c "
s.split(' ').join(' AND ')
# => "a AND b AND c"
This has the advantage of ignoring leading and trailing whitespace that Peter's RE does not:
s = " a b c "
s.gsub /\s+/, ' AND '
# => " AND a AND b AND c AND "
Removing whitespace
s.split(' ').join('')
# or
s.delete(' ') # only deletes space chars
use gsub method for replacing whitespace
s = "ajeet soni"
=> "ajeet soni"
s.gsub(" "," AND ")
=> "ajeet AND soni"

Resources