I have link like this:
http://localhost:3000/sms/receive/sms-id=7bb28e244189f2cf36cbebb9d1d4d02001da53ab&operator-%20id=1&from=37126300682&to=371144&text=RV9+c+Dace+Reituma+0580913
I want to extract all diferent variable values from this link. For example sms-id,operator,from, to and text.
So far I have like this:
routes.rb
get 'sms/receive/:params', to: 'sms#receive'
SMS#RECEIVE controller
def receive
query = params[:params]
sms_id= query[/["="].+?[&]/]
flash[:notice] = sms_id
end
This gives me : =7bb28e244189f2cf36cbebb9d1d4d02001da53ab& but I need without the first = and last characher & .
If I try to add strings like :query[/["sms-id"].+?[&operator]/] that could allow me to extract all variables smoothly, it gives me error : empty range in char class: /["sms-id"].+?[&operator]/
But I believe there is other way to extract all these variable values in different way?
Thanks in advance!
The error in your regular expression is because the - is a reserved character when in-between square brackets. In this context, it must be escaped with a backslash: \-.
To parse your query string, you can do this:
sms_id = params[:params].match(/sms-id=([^&]*)/)[1]
or parse it with the more generic method:
parsed_query = Rack::Utils.parse_nested_query(params[:params])
sms_id = parsed_query['sms-id']
(quoted from this answer)
If you have control over the initial URL, change the last / for a ? for an even easier solution:
http://localhost:3000/sms/receive?sms-id=7bb28e244189f2cf36cbebb9d1d4d02001da53ab&operator-%20id=1&from=37126300682&to=371144&text=RV9+c+Dace+Reituma+0580913
and you will have sms-id in params:
sms_id = params['sms-id']
You need
get 'sms/receive/', to: 'sms#receive'
path in routes.rb and get params in the controller
Try this
matches = params[:params].scan(/(?:=)([\w\+]+)(?:\&)?/)
# this will make matches = [[first_match], [second_match], ..., [nth_match]]
# now you can read all matches
sms_id = matches[0][0]
operator_id = matches[1][0]
from = matches[2][0]
to = matches[3][0]
text = matches[4][0]
# and it will not contatin = or &
I suggest for you to make method in model or helper, and not to write whole code in controller.
Related
This url:
url = rtmp://xxxxxxxxxxxxxx.cloudfront.net/cfx/st/mp3:audios/lesson/2/cancion?Expires=1386332537&Signature=mysignature__&Key-Pair-Id=my-key-par-id
I would like to add the extension mp3 to all file name.
In this case the file name is cancion
The id of lesson is a dynamic value.
I would like to get this url something like:
url = rtmp://xxxxxxxxxxxxxx.cloudfront.net/cfx/st/mp3:audios/lesson/2/cancion.mp3?Expires=1386332537&Signature=mysignature__&Key-Pair-Id=my-key-par-id
Thanks!
You can parse the URI, edit the path, then return the value
require 'uri/http'
u = URI.parse('rtmp://xxxxxxxxxxxxxx.cloudfront.net/cfx/st/mp3:audios/lesson/2/cancion?Expires=1386332537&Signature=mysignature__&Key-Pair-Id=my-key-par-id')
u.path += ".mp3"
puts u.to_s
or use a simple regexp replace
u = 'rtmp://xxxxxxxxxxxxxx.cloudfront.net/cfx/st/mp3:audios/lesson/2/cancion?Expires=1386332537&Signature=mysignature__&Key-Pair-Id=my-key-par-id'
u.gsub('?', '.mp3?')
The second approach can be used only if you can assume the format of the input is always the same.
You can do simple gsub since this is URL and you can expect one occurrence of ? so simple do.
url.gsub!('?', '.mp3?')
Usually I would go regex here but no need from previously stated reason.
I need to translate a message key using a Hashmap using the Grails standard internationalization method.
I receive an Enum and a map with the binding, which are going to be replaced in the text.
The Enum indicates, which key is going to be recovered. The bindings have the values to replace on the translation.
messageSource.getMessage("mail.layout.subject.${templateName}",ARGS,"",locale)
The problem is that I need to pass the map to the args like an array, not like a map, but I don't know the order of the args.
My question is, if there are any ways to create a tranlation key like:
mail.layout.subject.ENUM1=Blablabl {name} bablablabl {age}
Instead of
mail.layout.subject.ENUM1=Blablabl {0} bablablabl {1}
Finally I did it with brute force. May be is not the best answer but I coudln't find any one better.
Basically I get the translation with te message resources and then I work with it finding my custom expresions.
def messageSource = grailsApplication.getMainContext().getBean('messageSource')
def subject = messageSource.getMessage("mail.layout.subject.NOTIFICATION",null,"",locale)
An example of subject resource
mail.layout.subject.NOTIFICATION=The user {friend.name} is friend of {user}
An example bindings:
def bindings = [friend:[name:"Jhon",surname:"Smith"],user:"David"]
With this senteces I replace my expresions with the value of the bindings
Pattern pattern = Pattern.compile("\\{[^}]+\\}")
def res = subject.replaceAll(pattern,{
def expresion = it[1..it.size()-2] // removes brackets
def fields = expresion.split("\\.");
def res = bindings
fields.each{
println(it)
res = res."${it}"
}
return res
})
After the proces the subject becomes like: "The user Jhon is friend of David"
The example use a HashMap of HashMaps, but it also works with object because grails/groovy handles the object like HashMaps and viceversa
This is much cleaner. :)
import groovy.text.SimpleTemplateEngine
def text = 'Dear "$firstname $lastname",So nice to meet you in ${city.name}.See you in ${month},${signed}'
def binding = ["firstname":"Sam", "lastname":"Pullara", "city":["name":"San Francisco", "id":"28"], "month":"December", "signed":"Groovy-Dev"]
def engine = new SimpleTemplateEngine()
template = engine.createTemplate(text).make(binding)
I've got a problem in doing some metaprogramming in Ruby / Rails which must be minor, but I can't get the clue.
I wan't to assign values to an active record relation, with my model having attributes:
MyModelClass.p1_id,
.p2_id,
...
.p8_id
SecondModel.position #Integer in (1..8)
I now want to do the following
sms = SecondModel.where(:xyz => 'bla')
sms.each do |sm|
mmc = MyModellClass.first
mmc.#somehow construct method here = sm.id
end
So that somehow this is accomplished
mmc.p1_id = sm.id
mmc.p2_id = sm.id
..
mmc.p8_id = sm.id
To sum up: I want to create that p*n*_id stuff dynamically, but I can't find out, how to tell Ruby, that this should be a method. I tried so far:
mmc.send('p#{sm.position.to_s}_id'.to_sym) = sm.id
But this doesn't work. Any clues?
You were close. Try this:
mmc.send("p#{sm.position.to_s}_id=", sm.id)
Here we call the method with = and pass the value of attribute as the second argument of send
I have an URL address that I change dynamically I it goes something like this:
The dynamic part is the -> edition = Model.Edition.Usually it as an integer value and the url ends up something like that: ....&edition=1232113 . Sometimes I need it to end up like that : &edition=1232113#10_11 and I managed to pass th right value to the edition placeholder but after the reload it doesn't show the same url that I expected it is similar but it substitutes the '#' with '%23'. And it looks something like that: 1232113%2310_11 and the effect is not what I expect.
From the other side, when I type it manually : 1232113#10_11 it works.
Can you help?
If you problem is concerning that the Url.Action is converting a part of your url, you may want to use the RAW method.
#Html.Raw(Url.Action("Method","Controller", new { Id = Model.DId, dbId = Model.DbId, iconId = Model.IconId, edition = Model.Edition })
Removing the query string from a URL in Ruby could be done like this:
url.split('?')[0]
Where url is the complete URL including the query string (e.g. url = http://www.domain.extension/folder?schnoo=schnok&foo=bar).
Is there a faster way to do this, i.e. without using split, but rather using Rails?
edit: The goal is to redirect from http://www.domain.extension/folder?schnoo=schnok&foo=bar to http://www.domain.extension/folder.
EDIT: I used:
url = 'http://www.domain.extension/folder?schnoo=schnok&foo=bar'
parsed_url = URI.parse(url)
new_url = parsed_url.scheme+"://"+parsed_url.host+parsed_url.path
Easier to read and harder to screw up if you parse and set fragment & query to nil instead of rebuilding the URL.
parsed = URI::parse("http://www.domain.extension/folder?schnoo=schnok&foo=bar#frag")
parsed.fragment = parsed.query = nil
parsed.to_s
# => "http://www.domain.extension/folder"
url = 'http://www.domain.extension/folder?schnoo=schnok&foo=bar'
u = URI.parse(url)
p = CGI.parse(u.query)
# p is now {"schnoo"=>["schnok"], "foo"=>["bar"]}
Take a look on the : how to get query string from passed url in ruby on rails
You can gain performance using Regex
'http://www.domain.extension/folder?schnoo=schnok&foo=bar'[/[^\?]+/]
#=> "http://www.domain.extension/folder"
Probably no need to split the url. When you visit this link, you are pass two parameters to back-end:
http://www.domain.extension/folder?schnoo=schnok&foo=bar
params[:schnoo]=schnok
params[:foo]=bar
Try to monitor your log and you will see them, then you can use them in controller directly.