I was going through the AR query interface guide and from it I got the impression that the Rails console should be interpreting the \n in the output from the .explain command as a newline, rather than printing it as raw text on the screen. Reading a query on one single line is inconvenient to say the least.
I can "fix" the formatting issue by prepending "print" to any ActiveRecord::Relation object output to the console, as in the canonical example:
print User.joins(:posts).explain
Is it supposed to work that way by default, or am I doing something wrong? Do people always stick to prepending print?
Thanks!
Yes, the rails console displays the \n characters (rather than rendering) them by default. I always add print exactly as you have done.
Seems normal.
>> hi = "hello\nworld"
=> "hello\nworld"
>> hi
=> "hello\nworld"
>> puts hi
hello
world
=> nil
If you just type a variable or method, it shows you a raw data dump of the value or return value.
Related
My sample text looks like this:
30","formatedMinDeliveryDate":null,"formatedMaxDeliveryDate":null,"actualDeliveryDate":null,"trackingNumber":"ID180135116580CN","shippmentTrackingUrl":"https:\u002F\u002Fwww.057872.m2749.l5119","localizedCurrency":null}},"actions":[{"label":"Leave feedback","icon":null,"value":null,"action":"link","actionParam":{"label":"LEAVE_FEEDBACK_FOR_SELLER","u
I want to get the number ID180135116580CN and I'm having trouble achieving this using regexp.
The file is full of them and I'm doing this
out_file = File.open('public/orders.txt').each do |line|
p line[/(?<="trackingNumber":")[^"]*(?=")/]
end
but it only prints nil and doesn't extract the number I'm looking for.
Is the regexp wrong or do I need to traverse the file differently?
Basically after every trackingNumber, I want to get whatever is in quotes there after.
Thanks!
Edit:
Attempted this as per #WiktorStribiżew suggestion in the comments
p line.scan(/"trackingNumber"\s*:\s*"([^"]+)"/)
Now, I'm getting all of trackingNumbers as an array like this
[["UB08578YP"], ["UB085789YP"], ["ID180135791CN"], ["ID180135728CN"]]
How do I modify this to get them in individual lines like this?
UB08578YP
UB085789YP
ID180135791CN
ID180135728CN
it can be simpler if you read the file completely and run the scan there something like this
file_content = open("./my_file.txt").read
results = file_content.scan(/(?<="trackingNumber":")[^"]*(?=")/)
puts results
It will have them formated. in the way you want it.
I need to find a section of a string that includes the substring "print time:" and save it with the time it displays after the colon on the database.
What I've used until now is the downcase helper and the includes? helper to start the search but I'm not sure how to actually execute a search inside the string.
How can I find the section of the string so that I can save it afterwards?
Use regular expressions, which in Ruby can be written with the /…/ syntax and matched against using String#match.
log = "username: jsmith\nprint time: 08:02:41\npower level: 9001"
print_time = log.match(/print time:\s*([^\n]+)\s*\n/)[1]
p print_time # => "08:02:41"
The regex /print time:\s*([^\n]+?)\s*\n/ matches any text after “print time:”, on the same line, ignoring surrounding whitespace \s*, and saves it as the first capture group using the (). Then [1] selects the contents of that first capture group.
After extracting the print_time string, you can do whatever you need to with it. For example, if you had a Rails model PrintTime, you might save the extracted time to the database with PrintTime.create(extracted_time: print_time).
I have a value called "FooBar". I want to replace this text with the quotes to Enr::Rds::FooBar without quotes.
Update:
For example, #question.answer_model gives the value "FooBar" (with the quotes)
I am a newbie and somebody please refer me how would i start to know about regex? What is the best way to practice in online?
Since you want to: a) drop the quotes and b) prepend FooBar with Enr::Rds::, I would suggest you preform exactly what is intended, literally:
'"FooBar"'.delete('"').gsub(/\A/, "Enr::Rds::")
# => "Enr::Rds::FooBar"
I think you are trying to convert a string to a constant. try the following
"Enr::Rds::#{#question.answer_model.gsub('"', '')}".constantize.find(...)
The code itself would be in ruby. Idea is to make it interactive for user. For instance, code asks:
what is your name?
user input "John"
Hi John!
I know I can make it <%...%>. I want to make it in a separate ruby.rb file that would be "uploaded" via form in new template. In show template results of code would be displayed. Any gem for this sort of interactivity?
Looking forward
Thanks
This is incredibly bad practice, and should never be used without sanitizing input, but Ruby has an eval statement. Pass it a string (such as a param POSTed by your form), and it'll evaluate that string as Ruby and return the result.
x = 5
eval "x / 2.5"
=> 2.0
If you're expecting a .rb file to be uploaded, you can read that file and pass the contents to eval.
But remember, treat all input as hostile.
I'm trying to store regexes in a database but they're not working when used in a .sub(), even though the same regex works when used directly in .sub() as a string.
regex = Class.object.field // Class.object is an active record containing "\w*\s\/\s"
mystring = "first / second"
mystring.sub(/#{regex}/, '')
// => nil
mystring.sub(/\w*\s\/\s/, '')
// => second
Any insight appreciated!
Thanks,
Matt.
Editing to correct class/object terminology (thanks) & correcting my 2nd example as I had shown #{} wrapped around the working regex (cut & paste SNAFU).
To answer your question: It is not quite what kind of thing your Class.object is. If it's an ActiveRecord, it won't work.
Edit: You obviously found that the problem is Rails escaping the regexp.
An ActiveRecord cannot "contain" your regular expression directly; the regexp will be in one of the fields of your record. In which case you'd want to do something like regexp = Class.object.field_containing_the_regexp.
Even if that is not the case, I suspect that the problem is that your regexp is something other than a string. You can quickly test this by using
puts "My regexp: #{regexp}"
The string that you will see in the output will be the one that is used for the regexp.
A String is not a Regexp. You have to create a Regexp object first.
regex = Regexp.new("\w*\s\/\s")
Turns out my regexp didn't cater for all cases - \w didn't account for symbols. After checking in rails console, and seeing the screwey escaping I was alreasdy half-way down the wrong track.
Thanks for the help.