Lets say I have a rails application in which code is pasted into the content text box like the following.
Pasted Code
Person name
Person name
Person name
Person name
It is put into the database with the proper new lines after each line according to my server log.
What I want to do is in the show action I want to output this text after removing any blank spaces between names and remove any double names and put them in alphabetical order.
I also want to add an html option tag around them.
I have already written a program in Java to do this using sets. I was wondering how to approach this in rails. I would assume the code to do this would go in the controller.
My second question was in the index action. It shows all the pasted items. How can I only show a snippet of what was actually pasted. Lets say 20 characters long? Thanks!
removing any blank spaces between names
have no idea what 'blank spaces between' means, but I assume you want to remove 'blank lines':
lines = code.split(/\n\r?/).reject { |l| l.strip.empty? }
remove any double names
lines = lines.uniq # or uniq!
put them in alphabetical order
lines = lines.sort # or sort!
add an html option tag around them
options_str = lines.map { |l| "<option value='#{l}'>#{l}</option>" }.join('\n') # Do not forget to escape html
Or if you want it shorter:
code.split(/\n\r?/).reject { |l| l.strip.empty? }.uniq.sort.map do |l|
"<option value='#{l}'>#{l}</option>"
end.join('\n')
That should give you a tip.
The most important thing for you would probably be having String, Array and Enumerable documentation in front of you.
Related
I would like to have an input-field on my webpage, which allows users to interact with models and perform specific searches within specified models. The system should support various actions, primarily add (+), delete (!) and search (?).
To add a new Todoitem to a todolist, the syntax would be like this:
+todoitem Some text here #todolistname
To delete a post, the syntax would be like this:
!post nameofpost
To search for a post, the syntax would be:
?post nameofpost
The previous examples adds and removes items from the current signed in user. I would also like the command line to support groups (identified by .groupname)
A valid syntax to add a todoitem to todolist with name important
ingroup school would be: +todoitem Some todo text #important.school
Searching for all posts in a group would be: ?post .group
Spaces and order should not matter, except for actual content to be added to model (like the todo text of a todo item). That means +todoitem.school#important Some todo text should give the same result as the input in #1.
Could anyone help me with a way of implementing this effectively in rails? That is how you could effectively search the input-string, decide what the user is trying to do (based on the prefix identificators), and then parsing the input into actual queries ?
Edit:
To clarify the last paragraph, as I might have misused the word 'parsing', I was thinking of going through the input-string letter by letter, and then branching/dividing the information so that it can be easily used by pre-defined functions (which perform the queries).
I'm implementing an entry field where users can enter tags. Once a tag is recognized, it is replaced by a UICollectionViewCell that makes the tag look prettier.
It looks something like this:
Now I would like to add the possibility to add another tag by just typing after the end of the current list of tags. Is there a way to do this? I was thinking of adding a cell with a UITextField in it or something similar, but that would create problems if I had to do line wrapping, since there might arise a situation where the user would've entered the first two tags on the picture above, and then I'd want a cursor to appear right after them. However, this would require adding a cell that would not be rectangular (if the user filled the entire first line, it'd have to wrap back to the beginning of the next line).
How is this usually done?
To clarify, if I added a text view to the end and the user entered something spanning multiple lines, it would probably wrap like this:
TAG1 TAG2 XXXXXX
XXXXXX
XXXXXX
XXXXXX
Instead of wrapping like this:
TAG1 TAG2 XXXXXX
XXXXXXXXXXXXXXXX
Try this one here. There are other tag controls that might be suitable. Just browse this site, its quite resourceful and free.
I have a string. That string is a html code and it serves as a teaser for the blog posts I am creating. The whole html code (teaser) is stored in a field in the database.
My goal: I'd like to make that when a user (facebook like social button) likes certain blog post, right data is displayed on his news feeds. In order to do that I need to extract from the teaser in the first occurrence of an image an image path inside src="i-m-a-g-e--p-a-t-h". I succeeded when a user puts only one image in teaser, but if he accidentally puts two images or more the whole thing craches.
Furthermore, for description field I need to extract text inside the first occurrence inside <p> tag. The problem is also that a user can put an image inside the first tag.
I would very much appreciate if an expert could help me resolve this what's been bugging me for days.
Text string with a regular expression for extracting src can be found here: http://rubular.com/r/gajzivoBSf
Thanks!
Don't try to parse HTML by yourself. Let the professionals do it.
require 'nokogiri'
frag = Nokogiri::HTML.fragment( your_html_string )
first_img_src = frag.at_css('img')['src']
first_p_text = frag.at_css('p').text
I am trying to put the values of some xml elements into an array using rexml. Here is an example of what I am doing:
doc = Document.new("<data><title>This is one title</title><title>This is another title</title></data>")
XPath.each( doc, "*/title") { |element|
puts element.text
}
However, that outputs:
[<title> ... </>, <title> ... </>]
How can I get it to output an array containing "This is one title" and "This is another title"?
Moving my comment to an answer, per request:
While puts may convert its argument its argument to a string anyway, you can have the XPath return the text node in the first place:
XPath.each(doc, "*/title/text()") {...
Are you sure about that? Here's a complete program:
#!/usr/bin/ruby
require 'rexml/document'
include REXML
doc = Document.new("<data><title>This is one title</title><title>This is another title</title></data>")
XPath.each( doc, "*/title") { |element|
puts element.text
}
Output:
This is one title
This is another title
Edit: It sounds like the OP has moved on, but I think there should be some clarification added here for future visitors. I upvoted #LarsH's good answer, but it should be noted that, given the OP's specific input, element.text should produce exactly the same output as would result from selecting the text() nodes in the first place. From the docs:
text( path = nil )
A convenience method which returns the String value
of the first child text element, if one exists, and nil otherwise.
The sample input given in the original question shows <title> elements containing only one text node in each case. Therefore, these two methods are the same (in this case).
However, pay attention to this important note:
Note that an element may have multiple Text elements, perhaps
separated by other children. Be aware that this method only returns
the first Text node.
You can get all of an element's child text nodes using texts() (plural).
What I suspect a lot of people are really looking for is an equivalent of the DOM's textContent (or its illegitimate cousin innerText). Here's how you might do that in Ruby:
XPath.each(doc, "*/title") { |el|
puts XPath.match(el,'.//text()').join
}
This joins all of the text descendants of each element into a single string.
The short answer is that there's no short answer. Which one of these you want, if any, is highly context-specific. The only requirement in the original question is to "put the values of some xml elements into an array", which isn't really much of a specification.
I have a table in my rails project, which contains a column of type string. One of the entries for this column is "one\ntwo". When I try to display the table, that entry is displayed as "one two". I serialized the entry, so I tried displaying an inspected version as well, which displayed "one\ntwo". Is there any way to display that entry as following?
one
two
s.gsub(/\n/, '<br>') try this, and play with sanitize or maybe html_safe