I've a very simple problem. I want to construct a encoded url from an object. I've an object called "invitation". "invitation" has following fields, "message", "date", "name". I want to construct a following encoded string from this object. So when I use this url, it will pre-fill google mail's compose form.
https://mail.google.com/mail/u/0/?view=cm&fs=1&su=Party+on+date&body=%0Amessage%0Ahttp://localhost:3000/invitations/3%0Aname%0A&tf=1
I've declared a helper as shown below (which suppose to return an encoded string and can be use in a view). ..
module ApplicationHelper
def google_mail_encoded_url(invite)
uri = URI.parse('https://mail.google.com/u/0/?')
uri.query = URI.encode_www_form('view'=> "cm", 'fs' => "1", 'su' => "Party on " + invite.date, 'body' => "\nHi,\n" + invite.message + "\n" + invitations_url(invite))
puts uri.to_s
end
end
I tried following in rails console,
#invite = Invitations.where(:id => 10)
helper.google_mail_encoded_url(#invite) #just to see the output....
This fails with NameError: undefined local variable or method `invitations_url' for main:Object. Is this the correct way to call and construct encoded url? Any help is appreciated.
That is because the routes are not loaded when you open a console.
To be able to use them run the following in your console:
> include Rails.application.reload_routes!.first.url_helpers
=> Object
> root_path
=> "/"
Related
Hi i had created a small ruby project which consists of JSON file. I stored the JSON data into hash keys. AND worte a method to access the data which is present in hash key using user input. But when i try to send use the user input i am getting this error
how_many_ingredients': undefined methodkeys' for nil:NilClass (NoMethodError)
I found this link with same question and tried that solution but still i'm getting the same error
Accessing Hash Keys with user inputted variables, NoMethodError
File one where all the methods are written
require 'json'
class Methods
attr_accessor :name, :text
def initilize(name)
#name = name
#text = text
end
def how_many_ingredients(text)
puts 'text'
file = File.read('a.json')
hash = JSON.parse(file)
#puts hash['recipes']['pizza'].keys
puts hash['recipes'][text].keys
end
end
File 2 where how_Many_ingredients method is accessed, I can see that the variable is passed to that method
require './1'
class Hello < Methods
person = Methods.new
person.test
puts "enter recipie"
person.name
str = gets
person.how_many_ingredients str
end
Note that when you use gets, the input can contain newline and carriage return characters. You'll need to use gets.chomp to filter these. This is likely the cause of the issue in your program.
Compare the following two:
> puts gets.size
"Hello!"
# 7
> puts gets.chomp.size
"Hello!"
# 6
Note that you'll still need to extend your program to account for user inputted keys that are not in your hash.
Your code assumes that there will always be a hash stored at hash['recipes'][text] - you need to cater to the cases where it isn't.
A simple way to do this is to work your way down through the hash with && symbols - if any step is nil (or false), the line will return nil (or false) rather than exploding. eg
puts hash['recipes'] && hash['recipes'][text].is_a?(Hash) && hash['recipes'][text].keys
Note i'm testing that hash['recipes'][text] is a hash (rather than just a string for example) before calling .keys on it.
A simple question:
In rails I get as response an hash like this:
{"success":true,"new_id":816704027}
So, the difference from a normal structure I guess is- "new_id": -instead of- new_id:
Does anyone know how to retrieve the data labelled "new_id"?
The usual array["new_id"] doesn't work.
The response to the code:
new_customer_id = #response.body
puts new_customer_id
puts new_customer_id["new_id"]
is simply:
=> {"success":true,"new_id":816704028}
=> new_id
I come from the implementation of JSON_response. Anyway, they changed the app and I don't have anymore a JSON message, but they use the method:
return_200(additional_items: {:new_id => "#customer.id"} )
More:
If I write:
new_customer_id = #response.body
puts new_customer_id
puts new_customer_id[:new_id]
the answer printed is simply:
=> {"success":true,"new_id":816704028}
and the request for the :new_id content does not to be received.
Much more interesting is the following:
After the fact that:
puts new_customer_id["new_id"]
prints:
=> new_id
If I write:
puts new_customer_id["new_id"][0]
puts new_customer_id["new_id"][1]
puts new_customer_id["new_id"][2]
...
I obtain:
=> n
=> e
=> w
...
Also:
if I write:
puts new_customer_id["new_"]
puts new_customer_id["new_i"]
I obtain:
=> new_
=> new_i
and if I write:
puts new_customer_id["new_id_anyOtherCharacter"]
I get nothing
Luca
That's not a ruby object you are getting back. It's JSON. You can get the new_id in a variety of ways:
JSON.parse(#response.body)["new_id"]
JSON.parse(#response.body).symbolize_keys[:new_id]
JSON.parse(#response.body).with_indifferent_access[:new_id]
I bet the hash has a symbol key instead of a string key. Try with array[:new_id].
use params to get the value like:
new_id= array[:new_id]
I have the following 3 strings...
a = "The URL is www.google.com"
b = "The URL is google.com"
c = "The URL is http://www.google.com"
Ruby's URI extract method only returns the URL in the third string, because it contains the http part.
URI.extract(a)
=> []
URI.extract(b)
=> []
URI.extract(c)
=> ["http://www.google.com"]
How can I create a method to detect and return the URL in all 3 instances?
Use regular expressions :
Here is a basic one that should work for most cases :
/(https?:\/\/)?\w*\.\w+(\.\w+)*(\/\w+)*(\.\w*)?/.match( a ).to_s
This will only fetch the first url in the string and return a string.
There's no perfect solution to this problem: it's fraught with edge cases. However, you might be able to get tolerably good results using something like the regular expressions used by Twitter to extract URLs from tweets (stripping off the extra leading spaces is left as an exercise!):
require './regex.rb'
def extract_url(s)
s[Twitter::Regex[:valid_url]]
end
a = "The URL is www.google.com"
b = "The URL is google.com"
c = "The URL is http://www.google.com"
extract_url(a)
# => " www.google.com"
extract_url(b)
# => " google.com"
extract_url(c)
# => " http://www.google.com"
You seem to be satisfied with Sucrenoir's answer. The essence of Sucrenoir's answer is to identity a URL by assuming that it includes at least one period. if that is the case, Sucrenoir's regex can be simplified (not equivalently, but for the most part) to this:
string[/\S+\.\S+/]
This is something I used a while ago, hopefully it helps
validates :url, :format =>
{ :with => URI::regexp(%w(http https)), :message => "Not Valid URL" }
Pass it through that validation (I assume your using a database)
Try with this method. Hope it will work for you
def get_url(str)
arr = str.split(' ')
url = nil
arr.map {|arr_str| url = arr_str if arr_str.include?('.com')}
url
end
This is your example
get_url("The URL is www.google.com") #=> www.google.com
get_url("The URL is google.com") #=> google.com
get_url("The URL is http://www.google.com") #=> http://www.google.com
Here i am trying to pass one ID with the url, but that ID didn't append with URL...
def retrieve
url = "http://localhost:3000/branches/"
resource = RestClient::Resource.new url+$param["id"]
puts resource
end
giving ID via commend line that is
ruby newrest.rb id="22"
I have got the error like this
`+': can't convert nil into String (TypeError)
But all this working with mozilla rest client. How to rectify this problem?
Like this:
RestClient.get 'http://localhost:3000/branches', {:params => {:id => 50, 'name' => 'value'}}
You can find the command line parameters in the global ARGV array.
If ruby newrest.rb 22 will do then just
id = ARGV[0]
response = RestClient.get "http://localhost:3000/branches/#{id}"
puts response.body
Here are some examples from the documentation:
private_resource = RestClient::Resource.new 'https://example.com/private/resource', 'user', 'pass'
RestClient.post 'http://example.com/resource', :param1 => 'one', :nested => { :param2 => 'two' }
Just experiment with comma-separated parameters or with hashes so see what your URL gives you.
From my point of view line puts resource seems strange,
but when we leave it as it is
I'd suggest
def retrieve
url = "http://localhost:3000/branches/"
resource = RestClient::Resource.new url
res_with_param = resource[$param["id"]]
puts res_with_param
end
I haven't tried so there may be a syntax mistakes.
I'm really newcomer in ruby.
But idea is good I hope.
Greetings,
KAcper
I'm just starting to learn Ruby, and I've been following Why's (poignant) guide. At one point, I create a file titled 'wordlist.rb', within which is the following code:
code_words = {
'starmonkeys' => 'Phil and Pete, those prickly chancellors of the New Reich',
'catapult' => 'chucky go-go', 'firebomb' => 'Heat-Assisted Living',
'Nigeria' => "Ny and Jerry's Dry Cleaning (with Donuts)",
'Put the kabosh on' => 'Put the cable box on'
}
Another script calls the 'require' method on the wordlist file....
require 'wordlist'
# Get evil idea and swap in code words
print "Enter your new idea: "
idea = gets
code_words.each do |real, code|
idea.gsub!( real, code )
end
# Save the jibberish to a new file
print "File encoded. Please enter a name for this idea: "
idea_name = gets.strip
File::open( "idea-" + idea_name + ".txt", "w" ) do |f|
f << idea
end
Now, for whatever reason, I get this error when I try to run the script above:
test.rb:5: undefined local variable or method `code_words' for main:Object (NameError)
It's definitely finding and loading the wordlist.rb file (the method is returning true), but I can't seem to access the code_words Hash. Any idea what could be causing this?
code_words is a local variable inside wordlist.rb.
What you can do:
define a gloibal variable ( $wordlist)
define a constant (WORDLIST)
define another container, e.g. a class which provides the data