Ruby no method error with HTTParty - ruby

I am trying to make a post request in Ruby and I am getting inconsistent behaviour. I am currently using ruby-2.0.0-p598 on OSX.
When using PRY and I type the following post command:
HTTParty.post(#base_uri + '/method/?argument1&api_key=' + #api_key)
I get a successful respond from the API. However when I run it through my specs or inside the class I get:
undefined method `+' for nil:NilClass
I know it has to do with the plus sign, but I find it weird that I am getting a different behaviour. Can you please suggest what is the correct way of doing this?
Thanks in advance.

Good day
Behavior correct - some variable = nil.
You have check variables, or (in this case it is better not to do) call to_s:
HTTParty.post(#base_uri.to_s + '/method/?argument1&api_key=' + #api_key.to_s)

It looks like #base_uri and/or #api_key is null. Please double check if they are initialized with valid strings or not. Then try
HTTParty.post("#{#base_uri}/method/?argument1&api_key=#{#api_key}")
In this case, ruby will automatically try to convert #base_uri and #api_key to string so no need to call to_s method explicitly.

Related

How to call a method on a local variable in Ruby?

Probably a stupid question but I was following along this article and came across a bit of code I couldn't quite grasp. Here it is:
class CreateArticle
attr_reader :validate_article, :persist_article
def initialize(validate_article, persist_article)
#validate_article = validate_article
#persist_article = persist_article
end
def call(params)
result = validate_article.call(params)
if result.success?
persist_article.call(params)
end
end
end
More specifically, the problematic line is this:
if result.success?
Here's my problem with it: where did the success? method come from? It's not default in Ruby, and result is a local variable, so it should be nearby. But even if it's just omitted in the code sample, where would it have to be defined for that line to work? Everywhere I tried to define it just gave me an 'undefined method' error.
For example, I tried to define it both in the CreateArticle class and in the (only alluded to) ValidateArticle class, the obvious culprits, but no dice.
Update:
The reason I ask is not so much about what success? does as it is because I'm interested in using the pattern in my code. So, for example, my version of the success? method could be just checking whether a value got updated, or an item was inserted into an array. For example, let's say it's just this:
def success? # or self.success?
return true
end
Problem is, I can find no place where I can put this that works. I even created a module just for it and included it into the class, and still it doesn't work (it just returns 'undefined method'). So I'm still at a loss as to where I would have to define such a method so that it would work the way it looks like it should.
It's a method that comes with rails. It checks.for a server response with a 200 code. If it gets a 200 code it returns true else it returns false. Read the rails API docs about it... https://apidock.com/rails/v3.2.3/ActiveResource/Response/success%3F
Actually . success? is a built in ruby method. Check here. What it actually does is checking Stat and returns a boolean.
I did some more digging around the blog and from what I found I suspect that the code is probably making use of the dry-monads gem:
You can explicitly check the type by calling failure? or success? on a monadic value.
It's not explicit in the code excerpt but it's the only thing that makes sense.

Passing Boolean value as a String to a method expecting a String

In Ruby, I'm attempting to pass a boolean result to a method which accepts as a string as a parameter. This is as an experiment.
fileexists = File.file?("#{$fileLocation}")
puts File.file?("#{$fileLocation}")
puts fileexists
puts fileexists.to_s
This will result in:
true
true
true
Now if I attempt to call a method which accepts a string and pass this parameter in a number of ways.
slack(message: "#{fileexists}")
Results in the error message.
'message' value must be a String! Found TrueClass instead.
Which confuses me as I understand that Ruby evaluates anything within "" as a String. So placing a TrueClass object within a placeholder, should effectively cast this value to a string.
So let's try something slightly different:
slack(message: "#{fileexists.to_s}")
This results in the same error.
'message' value must be a String! Found TrueClass instead.
Now this is where things GET REALLY WEIRD!!
slack(message: "#{fileexists.to_s} ")
slack(message: "#{fileexists} ")
If I add a single bit of whitespace to the end of the string after the placeholder, it passes, and a slack message is sent my way, displaying 'true'.
I understand I may be asking for a bit of 'Crystal-ball' insight here as
I don't have the implementation of the 'slack' method, and this may be a result of the way that's implemented.
Does Ruby check types of params as they're passed like this?
Is that a Ruby standard error message you might receive, or a custom error thrown by the slack() method?
The dependency you are using, fastlane, auto-converts values that are passed into the actions (your call to slack).
The reason for this is that parameters in fastlane can also be specified via the commandline, so conversion is necessary. It converts your value of "true" to a boolean automatically because there is no Boolean class in ruby and the type of parameters is specified by giving it the name of a class, so it automatically converts "true" to a boolean. The offending line in the code is here.
As you can see in the code above, a workaround would be to do slack(message: "#{fileexists.to_s.capitalize}") or slack(message: fileexists ? "t" : "f"). Anything really as long as you avoid yes, YES, true, TRUE, no, NO, false, and FALSE
I understand I may be asking for a bit of 'Crystal-ball' insight here as I don't have the implementation of the 'slack' method, and this may be a result of the way that's implemented.
Sounds like youre using a lib (gem) which contains the methods slack, you can check the gem code location running gem which gem_name on your console.
Does Ruby check types of params as they're passed like this?
No
Is that a Ruby standard error message you might receive, or a custom error thrown by the slack() method?
Custom Error
As Jorg W Mittag stated this looks like a misimplementation of slack method when trying to deserialize, and then checking the types. You could fix the slack method on the gem by contributing to this gem, monkeypatch it or you can try to hack it the way it is... this last onde depends on how slack was implemented, maybe adding an extra pair of quotes, like "\"#{fileexists}\""
PS: You don't have to embbed the string inside another string if you're going to use it as it is, like fileexists = File.file? $fileLocation , this should work.
I'm only guessing here because we don't know what the method definition of slack is expecting an un-named String, but you're passing a hash.
slack(fileexists.to_s)

Unknown response for all methods and commands in ruby-asterisk

Testing ruby-asterisk manager interface with ruby version 1.9.3p0 and gem 1.8.11, for all command and methods its printing the the same output.
Anyone faced similar problem.
Code:
#!/usr/bin/env ruby
require 'ruby-asterisk'
#ami = RubyAsterisk::AMI.new("192.168.1.5",5038)
#ami.login("admin","passs")
puts #ami.command("sip show peers")
Output:
#<RubyAsterisk::Response:0x000000016af710>
Project URL
Problem solved. Didn’t check the readme RESPONSE OBJECT section.
It's working.
var = #ami.command(""sip show peers)
puts var.data
You are putting the Instance of the RubyAsterix. I think after haveing a brief look at the project that most/all of the instance methods returns the instance it self. The reason for doing it that way is that it makes it very easy to chain multiplie actions which makes for a nice syntax/usage.
I think you should remove the puts and allow the gem to display what it wants to display.

Ruby .include? method is not accepted as a valid method

I have this Ruby code in a script:
$dev_input=gets.chomp.downcase!
if $dev_input.include? "/"
check_developer_commands()
else
puts ">>Invalid Command<<"
continuing_dev_mode()
end
The problem is, whenever I try and run the script containing this, I get an error spat back at me that says :
dev_continue_main.rb:3:in 'continuing_dev_mode': undefined method 'include?' for nil:NilClass (NoMethodError)
Any idea what this error might be? I'm pretty sure that this is the proper way to use the .include? method. I've done some research, looked at tutorialspoint.com and some other sites, but they agree that this is the proper way to use this method.
I checked the error message and it confirmed that the third line in this script/my example is the source of the problem, so it's not some other instance of this method throwing an error.
Any thoughts? Please Help!
The problem is that $dev_input is nil. That stems from applying downcase! in defining $dev_input. I don't know why you want to possibly assign nil to $dev_input, and at the same time claim that calling include? on it is the right way. I don't get your intention for doing that, but if you instead had $dev_input = gets.chomp.downcase, then it wouldn't cause such error.

Rally API using Ruby: How do I reference the testcase method (Automated/Manual)?

I am using Ruby to work with the Rally API. I am trying to reference the testcase method. The method being Manual or Automated, but I always get an error. I am using Ruby, so I don’t know if method is a reserved word in Ruby, or what is happening. Could you please let me know how to reference the test case method?
I am able to do:
testcase.objective
testcase.priority
etc.
But I can’t do
testcase.method
I always get this error.
‘method’: wrong number of arguments (0 for 1) (ArgumentError)
Are you using rally_rest_api or rally_api?
If you are using rally_rest_api - Charles is correct. try testcase.elements[:method]
(fieldname downcased and underscored as a symbol)
If you are using rally_api - http://rubygems.org/gems/rally_api -
Getting fields can just be:
testcase["FieldName"]
Hope that helps.
You just need to capitalize the names when trying to access built-in fields (i.e. fields that are not custom). I came across this problem myself and using tc.Method instead of tc.method fixed it.
The reason this error shows up can be seen in the docs for Object#method which, as you've likely figured out by now, causes your code to call the method method instead of access the field named method.

Resources